/*   
 * Copyright (c) 2010-2020 DMGIS Ltd. All Rights Reserved.   
 *   
 * This software is the confidential and proprietary information of   
 * DMGIS. You shall not disclose such Confidential Information   
 * and shall use it only in accordance with the terms of the agreements   
 * you entered into with DMGIS.   
 *   
 */
package com.dmgis.qxfw.dataservice.bigdata.service.impl;



import com.dmgis.entity.DmMapPoint;
import com.dmgis.qxfw.dataservice.bigdata.service.IWeatherForecastService;
import com.dmgis.qxfw.dataservice.businessservice.api.domain.DbConfig;
import com.dmgis.qxfw.dataservice.businessservice.api.domain.RequestDataBySelect;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.qx.*;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.yj.dz_warning;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.zy.*;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.*;
import com.dmgis.qxfw.dataservice.businessservice.common.entity.ActualData;
import com.dmgis.qxfw.dataservice.businessservice.common.entity.Doppler;
import com.dmgis.qxfw.dataservice.businessservice.common.util.*;
import com.dmgis.qxfw.dataservice.businessservice.controller.ProcessRequestController;
import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.dataservice.service.Impl.FileRequestService;
import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.dataservice.service.Impl.MongoService1;
import com.dmgis.qxfw.dataservice.businessservice.yysl.service.CommonDao;
import com.dmgis.qxfw.dataservice.commonservice.utils.PGUtil;
import com.dmgis.qxfw.dataservice.gisservice.service.ITransformService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.github.kevinsawicki.http.HttpRequest;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xml.sax.InputSource;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.StringReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * This class is used for ...
 * 
 * @author dsq
 * @version 1.0, 2018年10月31日 上午8:59:34
 */
@Service("WeatherForecastServices")
public class WeatherForecastServiceImpl implements IWeatherForecastService {

	ProcessRequestController pc = new ProcessRequestController();

	@Resource
	private ITransformService transformService;

	private  final String operatingSystem;

	@Autowired
	public WeatherForecastServiceImpl(String operatingSystem) {
		this.operatingSystem = operatingSystem;
	}


	String result = "";

	//MongoService1 ms = new MongoService1();
	FileRequestService ms = new FileRequestService();

	@Override
	public WeatherInfo getCityWeather(String county, String idOrName, String sc, String date, String localFlag) {
		String stationId = "";
		if ("false".equals(localFlag)) {
			XYInfo pos = getXYInfo(idOrName);
			// 获取站点编号
			stationId = GetNearestStaIdByXY(pos.getX(), pos.getY(), pos.getCity());
		} else {
			stationId = idOrName;
		}
		WeatherInfo result = new WeatherInfo();
		SmallStation skList = new SmallStation();
		CzStation[] fcstList = null;
		WarningInfo[] waringList = null;// 预警信息
		ZhishuInfo[] zhishuList = null;
		Richuriluo[] richuriluoList = null;
		// 判断当前县区是否属于益阳市
		String obj = CommonDao.getGoverInfo(county);
		String city = obj.split("\\|")[0];
		if (city.indexOf(DbConfig.CITY) >= 0) {
//			zhishuList = getZhiShuInfo1("", county.substring(0, county.length() - 1));// 本地制作指数信息
			zhishuList = getZhiShuInfo1("", county.substring(0, county.length() - 1));// 本地制作指数信息
			skList = getSKInfoList(stationId, "0");// 实况信息
			//  益阳市市预警
			waringList = getWarning(city);
			String strdate = date;
			if (skList != null && skList.getTime() != null) {
				strdate = skList.getTime();
			}
			fcstList = getCityYBInfoList(stationId, sc, strdate);//两表联查
			if (fcstList == null || fcstList.length < 1) {
				fcstList = getYBInfoList(stationId, sc, strdate);// 预报信息;  两表联查
			}
		} else {
			skList = getSKInfoList(stationId, "0");// 实况信息
			String strdate = date;
			if (skList != null && skList.getTime() != null) {
				strdate = skList.getTime();
			}
			//zhishuList = getZhiShuInfo2(county, county);// 网络指数信息
			fcstList = getYBInfoList(stationId, sc, strdate);// 预报信息;
		}
		//根据stationId获取该站点的经纬度信息
		List<Double> lonlat = getLonLatbyId(stationId);// 经纬度;
		if (lonlat != null && lonlat.size() > 0) {
			Double lon = lonlat.get(0);
			Double lat = lonlat.get(1);
			richuriluoList = SunTimesUtil.main(lon, lat);
		}
		result.setSkInfo(skList);
		result.setForecast(fcstList);
		result.setWaringInfo(waringList);
		result.setZhishuList(zhishuList);
		result.setRichuriluoList(richuriluoList);
		return result;
	}

	private List<Double> getLonLatbyId(String stationId) {
		String result = "";
		List<Double> resultList = new ArrayList<>();
		try {
			RequestDataBySelect dataBySelect = new RequestDataBySelect();
			dataBySelect.setParam("stationid='" + stationId + "'");
			Map<String, String> map = new HashMap<String, String>();
			map.put("param", JsonUtil.object2Json(dataBySelect));
			map.put("method", "smallscale_station");
			map.put("sqlType", "select");
			result = pc.processRequest(map);
			if (result.equals("")) {
				result = "[]";
			}
			List<smallscale_station> list = new ArrayList<smallscale_station>();
			list = JsonUtil.jsonStr2TypeReference(result, new TypeReference<List<smallscale_station>>() {
			});
			if (list != null && list.size() > 0) {
				resultList.add(list.get(0).getLongitude());
				resultList.add(list.get(0).getLatitude());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultList;

	}

	private CzStation[] getCityYBInfoList(String stationId, String sc, String strdate) {

		SimpleDateFormat sdf1 = new SimpleDateFormat("HH");
		Date dates = new Date();
		String datechar1 = sdf1.format(dates);
		int s = Integer.parseInt(datechar1);
		String ss = "08";
		if (s >= 8 && s <= 20) {
			ss = "08";
		} else {
			ss = "20";
		}

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
		List<CzStation> result = new ArrayList<CzStation>();// 预报结果
		List<forecastinfotemp> resultList = new ArrayList<forecastinfotemp>();
		Map<String, String> selectParam = new HashMap<String, String>();
		RequestDataBySelect selectRequest = new RequestDataBySelect();

		// 条件where
		StringBuilder strWhere = new StringBuilder();
		int whereCount = 0;
		if (!StringUtil.IsNullOrEmpty(stationId)) {
			strWhere.append(String.format("and stationid='%s'", stationId));
		}
		if (strdate != null) {
			strWhere.append(String.format(" and datechar='%s'", strdate.substring(0, 10) + " 00:00:00"));
		}
		strWhere.append(String.format(" and timechar='%s'", ss));
		if (whereCount == 0 && !StringUtil.IsNullOrEmpty(strWhere.toString())) {
			strWhere = strWhere.replace(0, 4, "");
		}

		selectRequest.setParam(strWhere.toString());
		selectRequest.setSort(new String[]{"stationid asc", "ntimes asc"});
		try {
			selectParam.put("method", "forecastinfo");
			selectParam.put("sqlType", "select");
			selectParam.put("param", JsonUtil.object2Json(selectRequest));
			String message = pc.processRequest(selectParam);
			resultList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<forecastinfotemp>>() {
			});
			WebCtrlData wcd = new WebCtrlData();
			SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

			for (int i = 0; i < resultList.size(); i++) {
				String Windd = "";
				String Windv = "";
				CzStation fcstInfo = new CzStation();
				fcstInfo.setMinTemp(resultList.get(i).getMintemp().toString());
				fcstInfo.setMaxTemp(resultList.get(i).getMaxtemp().toString());
				if (resultList.get(i).getWind1().equals(resultList.get(i).getWind2())) {
					Windv = wcd.GetWeatherFs(resultList.get(i).getWind1().toString());
				} else {
					Windv = wcd.GetWeatherFs(resultList.get(i).getWind1().toString().trim()) + "转" + wcd.GetWeatherFs(resultList.get(i).getWind2().toString().trim());
				}

				if (resultList.get(i).getWindd1().equals(resultList.get(i).getWindd2())) {
					Windd = wcd.GetWeatherFx(resultList.get(i).getWindd1().toString());
				} else {
					Windd = wcd.GetWeatherFx(resultList.get(i).getWindd1().toString().trim()) + "转" + wcd.GetWeatherFx(resultList.get(i).getWindd2().toString().trim());
				}
				fcstInfo.setId(resultList.get(i).getStationid());
				String format2 = format.format(new DateTime(resultList.get(i).getDatechar()).AddHours(resultList.get(i).getNtimes() - 12).toDate());
				fcstInfo.setDate(format2);
				fcstInfo.setWindD(Windd);
				fcstInfo.setWindV(Windv);
				fcstInfo.setWeather1(resultList.get(i).getWeather1().toString().trim());
				fcstInfo.setWeather2(resultList.get(i).getWeather2().toString().trim());
				result.add(fcstInfo);
			}
			// 处理得到天气符号图片
			for (CzStation czStation : result) {
				String weather1 = czStation.getWeather1();
				String weather2 = czStation.getWeather2();
				int i = Integer.parseInt(weather1);
				int i1 = Integer.parseInt(weather2);
				if (i < 10) {
					weather1 = "0" + weather1;
				}
				if (i1 < 10) {
					weather2 = "0" + weather2;
				}
				czStation.setPic1(weather1);
				czStation.setPic2(weather2);
				czStation.setWeather1(wcd.GetWeatherTq(weather1));
				czStation.setWeather2(wcd.GetWeatherTq(weather2));
			}


		} catch (Exception e) {
			// TODO: handle exception
			System.err.println(e.getStackTrace());
		}
		CzStation[] czStations = new CzStation[result.size()];
		result.toArray(czStations);
		return czStations;
	}


	@Override
	public WeatherInfo getCityWeather(String name, String sc, String date) {
		String stationId = "";
		String skStationId = "";// 实况站点信息
		XYInfo pos = getXYInfo(name);
		WeatherInfo result = new WeatherInfo();
		skStationId = GetNearestStaIdByXY(pos.getX(), pos.getY(), pos.getCity());
		CzStation[] fcstList = null;
		if (pos.getCity().contains(DbConfig.CITY)) {
			stationId = GetNcNearestStaIdByXY(pos.getX(), pos.getY());
			fcstList = getTownYBInfoList(stationId, sc, date);
		} else {
			stationId = skStationId;
			fcstList = getYBInfoList(stationId, sc, date);// 预报信息
		}
		SmallStation skList = getSKInfoList(stationId, "0");// 实况信息
		result.setSkInfo(skList);
		result.setForecast(fcstList);
		return result;
	}

	@Override
	public SmallStation getSKInfoList(String stationid, String type) {
		String result = "";
		// TODO Auto-generated method stub
		SmallStation list = new SmallStation();
		try {
			RequestDataBySelect dataBySelect = new RequestDataBySelect();
			dataBySelect.setColumns(new String[]{"StationID ,StationName ,Longitude ,Latitude ,rain, DryBulbTemp ,RelHumidity , InstantWindV , InstantWindD , StationPress  ,observTime "});
			dataBySelect.setParam("StationID='" + stationid + "'");
			dataBySelect.setSort(new String[]{"observTime desc"});
			dataBySelect.setLimit(1);

			String tableName = "";
			Map<String, String> map = new HashMap<String, String>();
			if ("0".equals(type)) {
				tableName = "msgmediumsmallscale";
			}
			if ("1".equals(type)) {
				tableName = "msgmediumsmallscale";
			}
			if ("2".equals(type)) {
				tableName = "tour_smallscale";
				map.put("advCode", DbConfig.advCode);
			}


			map.put("param", JsonUtil.object2Json(dataBySelect));
			map.put("method", tableName);
			map.put("sqlType", "select");
			result = pc.processRequest(map);
			if (result.equals("")) {
				result = "[]";
			}


			if ("0".equals(type)) {
				List<msgmediumsmallscale_chn> smallStations = new ArrayList<msgmediumsmallscale_chn>();
				smallStations = JsonUtil.jsonStr2TypeReference(result, new TypeReference<List<msgmediumsmallscale_chn>>() {
				});
				if (smallStations != null && smallStations.size() > 0) {
					if ("0".equals(type) || "1".equals(type) || "2".equals(type)) {
						list.setId(smallStations.get(0).getStationid().replace("-65535.0", "-"));
						list.setTemp(smallStations.get(0).getDrybulbtemp().toString().replace("-65535.0", "-"));
						list.setRain(smallStations.get(0).getRain().toString().replace("-65535.0", "-"));
						list.setHumid(smallStations.get(0).getRelhumidity().toString().replace("-65535.0", "-"));
						list.setPress(smallStations.get(0).getStationpress().toString().replace("-65535.0", "-"));
						list.setWindV(smallStations.get(0).getInstantwindv().toString().replace("-65535.0", "-"));
						list.setWindD(WebCtrlData.GetAllFx(smallStations.get(0).getInstantwindd().toString().replace("-65535.0", "-")));
						list.setTime(new DateTime(smallStations.get(0).getObservtime()).toDateTimeString());
					}
				}

			}
			if ("1".equals(type)) {
				List<msgmediumsmallscale> smallStations = new ArrayList<msgmediumsmallscale>();
				smallStations = JsonUtil.jsonStr2TypeReference(result, new TypeReference<List<msgmediumsmallscale>>() {
				});
				if (smallStations != null && smallStations.size() > 0) {
					if ("0".equals(type) || "1".equals(type) || "2".equals(type)) {
						list.setId(smallStations.get(0).getStationid().replace("-65535.0", "-"));
						list.setTemp(smallStations.get(0).getDrybulbtemp().toString().replace("-65535.0", "-"));
						list.setRain(smallStations.get(0).getRain().toString().replace("-65535.0", "-"));
						list.setHumid(smallStations.get(0).getRelhumidity().toString().replace("-65535.0", "-"));
						list.setPress(smallStations.get(0).getStationpress().toString().replace("-65535.0", "-"));
						list.setWindV(smallStations.get(0).getInstantwindv().toString().replace("-65535.0", "-"));
						list.setWindD(WebCtrlData.GetAllFx(smallStations.get(0).getInstantwindd().toString().replace("-65535.0", "-")));
						list.setTime(new DateTime(smallStations.get(0).getObservtime()).toDateTimeString());
					}
				}


			}
			if ("2".equals(type)) {
				List<tour_smallscale> smallStations = new ArrayList<tour_smallscale>();
				smallStations = JsonUtil.jsonStr2TypeReference(result, new TypeReference<List<tour_smallscale>>() {
				});
				if (smallStations != null && smallStations.size() > 0) {
					if ("0".equals(type) || "1".equals(type) || "2".equals(type)) {
						list.setId(smallStations.get(0).getStationid().replace("-65535.0", "-"));
						list.setTemp(smallStations.get(0).getDrybulbtemp().toString().replace("-65535.0", "-"));
						list.setRain(smallStations.get(0).getRain().toString().replace("-65535.0", "-"));
						list.setHumid(smallStations.get(0).getRelhumidity().toString().replace("-65535.0", "-"));
						list.setPress(smallStations.get(0).getStationpress().toString().replace("-65535.0", "-"));
						list.setWindV(smallStations.get(0).getInstantwindv().toString().replace("-65535.0", "-"));
						list.setWindD(WebCtrlData.GetAllFx(smallStations.get(0).getInstantwindd().toString().replace("-65535.0", "-")));
						list.setTime(new DateTime(smallStations.get(0).getObservtime()).toDateTimeString());
					}
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public CzStation[] getYBInfoList(String stationid, String sc, String date) {
		List<CzStation> result = new ArrayList<CzStation>();// 预报结果
		WebCtrlData wcd = new WebCtrlData();
		try {
			//String strSql = "";
			DateTime dt1 = DateTime.parseDateTime(date);
			if ("08".equals(sc)) {

				//14条拼7
				RequestDataBySelect dataBySelect1 = new RequestDataBySelect();
				dataBySelect1.setColumns(new String[]{"StationID,DateChar,TimeChar,NTimes,Weather12,MaxTemp,MinTemp"});
				dataBySelect1.setParam("stationid='" + stationid + "' and datechar='" + dt1.toDateString() + "' and TimeChar='08'");
				dataBySelect1.setLimit(14);
				dataBySelect1.setSort(new String[]{"ntimes  asc"});
				Map<String, String> map1 = new HashMap<String, String>();
				map1.put("param", JsonUtil.object2Json(dataBySelect1));
				map1.put("method", "forecastinfo_chn");
				map1.put("sqlType", "select");
				String result2 = "";
				result2 = pc.processRequest(map1);
				if (result2.equals("")) {
					result2 = "[]";
				}
				List<forecastinfo_chn> list1 = new ArrayList<forecastinfo_chn>();
				list1 = JsonUtil.jsonStr2TypeReference(result2, new TypeReference<List<forecastinfo_chn>>() {
				});
				for (int i = 0; i < list1.size(); i += 2) {
					String max = "";
					String min = "";
					CzStation czStation2 = new CzStation();
					czStation2.setWeather1(list1.get(i).getWeather12());
					czStation2.setWeather2(list1.get(i + 1).getWeather12());
					if (Double.parseDouble(list1.get(i).getMaxtemp().toString().trim().replace("-65535", "0").replace(".0", "")) > Double.parseDouble(list1.get(i + 1).getMaxtemp().toString().trim().replace("-65535", "0").replace(".0", ""))) {
						max = list1.get(i).getMaxtemp().toString();
					} else {
						max = list1.get(i + 1).getMaxtemp().toString();
					}
					czStation2.setMaxTemp(max);
					if (Double.parseDouble(list1.get(i).getMintemp().toString().trim().replace("-65535", "0").replace(".0", "")) < Double.parseDouble(list1.get(i + 1).getMintemp().toString().trim().replace("-65535", "0").replace(".0", ""))) {
						min = list1.get(i).getMintemp().toString();
					} else {
						min = list1.get(i + 1).getMintemp().toString();
					}
					czStation2.setMaxTemp(max);
					czStation2.setMinTemp(min);
					czStation2.setId(list1.get(i).getStationid());
					czStation2.setDate(list1.get(i).getDatechar().toString());
					result.add(czStation2);
				}
			} else {
				RequestDataBySelect dataBySelect = new RequestDataBySelect();
				dataBySelect.setColumns(new String[]{"StationID,DateChar,TimeChar,NTimes,Weather12,MaxTemp,MinTemp"});
				dataBySelect.setParam("stationid='" + stationid + "' and datechar='" + dt1.toDateString() + "' and TimeChar='20' and MinTemp!='-65535' ");
				dataBySelect.setSort(new String[]{"ntimes  asc"});
				Map<String, String> map = new HashMap<String, String>();
				map.put("param", JsonUtil.object2Json(dataBySelect));
				map.put("method", "forecastinfo_chn");
				map.put("sqlType", "select");
				String result1 = "";
				result1 = pc.processRequest(map);
				if (result1.equals("")) {
					result1 = "[]";
				}
				List<forecastinfo_chn> list = new ArrayList<forecastinfo_chn>();
				list = JsonUtil.jsonStr2TypeReference(result1, new TypeReference<List<forecastinfo_chn>>() {
				});
				for (int i = 0; i < list.size(); i += 2) {
					String max = "";
					String min = "";
					CzStation czStation1 = new CzStation();
					czStation1.setWeather1(list.get(i).getWeather12());
					czStation1.setWeather2(list.get(i + 1).getWeather12());
					if (Double.parseDouble(list.get(i).getMaxtemp().toString().trim().replace("-65535", "0").replace(".0", "")) > Double.parseDouble(list.get(i + 1).getMaxtemp().toString().trim().replace("-65535", "0").replace(".0", ""))) {
						max = list.get(i).getMaxtemp().toString();
					} else {
						max = list.get(i + 1).getMaxtemp().toString();
					}
					czStation1.setMaxTemp(max);
					if (Double.parseDouble(list.get(i).getMintemp().toString().trim().replace("-65535", "0").replace(".0", "")) < Double.parseDouble(list.get(i + 1).getMintemp().toString().trim().replace("-65535", "0").replace(".0", ""))) {
						min = list.get(i).getMintemp().toString();
					} else {
						min = list.get(i + 1).getMintemp().toString();
					}
					czStation1.setMaxTemp(max);
					czStation1.setMinTemp(min);
					czStation1.setId(list.get(i).getStationid());
					czStation1.setDate(list.get(i).getDatechar().toString());
					result.add(czStation1);
				}
			}
			// 处理得到天气符号图片
			for (CzStation czStation : result) {
				String weather1 = czStation.getWeather1();
				String weather2 = czStation.getWeather2();
				czStation.setPic1(weather1);
				czStation.setPic2(weather2);
				czStation.setWeather1(wcd.GetWeatherTq(weather1));
				czStation.setWeather2(wcd.GetWeatherTq(weather2));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		CzStation[] czStations = new CzStation[result.size()];
		result.toArray(czStations);
		return czStations;
	}

	@Override
	public CzStation[] getTownYBInfoList(String stationid, String sc, String date) {
		List<CzStation> result = new ArrayList<CzStation>();// 预报结果
		try {
			String strSql = "";
			DateTime dt1 = DateTime.parseDateTime(date);

			strSql = String.format(
					"SELECT a.StationID as id,a.DateChar as date,a.TimeChar as timechar,b.NTimes AS NTimes1 ,a.NTimes AS NTimes2 "
							+ ",b.Weather1 AS weather1,a.weather1 AS weather2 ,case when a.MaxTemp > b.maxtemp THEN a.maxtemp ELSE b.maxtemp end AS maxTemp "
							+ ",case when a.MinTemp>b.mintemp then b.mintemp ELSE a.mintemp end  AS minTemp "
							+ "FROM township_forecasttemp AS a INNER JOIN township_forecasttemp AS b "
							+ "ON a.NTimes - b.NTimes = 12 AND a.StationID = b.StationID AND a.TimeChar = b.TimeChar AND a.DateChar = b.DateChar"
							+ " WHERE a.stationid = '%s' AND b.datechar = '%s'" + " ORDER BY  a.NTimes ASC limit 7",
					stationid, dt1.toDateString());
			result = PGUtil.getBeans(DbConfig.pg_url + DbConfig.qxConn, DbConfig.pg_userName, DbConfig.pg_pwd, strSql,
					CzStation.class);
			// 处理得到天气符号图片
			for (CzStation czStation : result) {
				String weather1 = czStation.getWeather1();
				String weather2 = czStation.getWeather2();
				czStation.setPic1(WebCtrlData.WeatherNameToPicPath(weather1.trim()));
				czStation.setPic2(WebCtrlData.WeatherNameToPicPath(weather2.trim()));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		CzStation[] czStations = new CzStation[result.size()];
		result.toArray(czStations);
		return czStations;
	}

	@Override
	public CzStation[] getTourInfoList(String date, String sc, String stationid) {
		CzStation[] result = null;// 预报结果
		//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
		String result1 = "";
		try {
			RequestDataBySelect dataBySelect = new RequestDataBySelect();
			dataBySelect.setColumns(new String[]{"StationID,StationName,Longitude, Latitude,Weather1,MaxTemp,MinTemp,WindS,WindD"});
			dataBySelect.setParam("DateChar ='" + date + "' and timechar='" + sc + "' and stationid='" + stationid + "' and ntimes<='24'");//date
			dataBySelect.setSort(new String[]{"StationID"});
			dataBySelect.setLimit(2);
			Map<String, String> map = new HashMap<String, String>();
			map.put("param", JsonUtil.object2Json(dataBySelect));
			map.put("method", "tour_fcst");
			map.put("sqlType", "select");
			result1 = pc.processRequest(map);
			if (result1.equals("")) {
				result1 = "[]";
			}
			List<tour_fcst> list = new ArrayList<tour_fcst>();
			list = JsonUtil.jsonStr2TypeReference(result1, new TypeReference<List<tour_fcst>>() {
			});
			tour_fcst tour_fcst = new tour_fcst();
			result = new CzStation[list.size() / 2];


			int index = 0;
			DateTime ybDate = DateTime.parseDateTime(date);
			for (int i = 0; i < list.size(); i += 2) {
				// String weather = "";
				String windV = "";
				String windD = "";
				Double maxTemp;
				Double minTemp;
				tour_fcst r1 = list.get(i);
				tour_fcst r2 = list.get(i + 1);
				String weather1 = r1.getWeather1().trim();
				String weather2 = r2.getWeather1().trim();
				String winds1 = String.valueOf(WebCtrlData.FengSuToFengJi(Double.parseDouble(r1.getWinds())))
						+ "级";
				String winds2 = String.valueOf(WebCtrlData.FengSuToFengJi(Double.parseDouble(r2.getWinds())))
						+ "级";
				String windd1 = WebCtrlData
						.GetAllFx(r1.getWindd().trim().replace("-65535", "-").replace(".0", ""));
				String windd2 = WebCtrlData
						.GetAllFx(r2.getWindd().toString().trim().replace("-65535", "-").replace(".0", ""));
				Double maxTemp1 = (Double) r1.getMaxtemp();
				Double maxTemp2 = (Double) r2.getMaxtemp();
				Double minTemp1 = (Double) r1.getMintemp();
				Double minTemp2 = (Double) r2.getMintemp();
				if (winds1.equals(winds2)) {
					windV = winds1;
				} else {
					int w2 = Integer.parseInt(winds2.substring(0, winds2.indexOf("级")));
					int w1 = Integer.parseInt(winds1.substring(0, winds1.indexOf("级")));
					if (w1 > w2) {
						windV = "<=" + w1 + "级";
					} else
						windV = "<=" + w2 + "级";
				}
				if (windd1.equals(windd2)) {
					windD = windd1;
				} else {
					windD = windd1 + "转" + windd2;
				}
				if (maxTemp1 > maxTemp2) {
					maxTemp = maxTemp1;
				} else {
					maxTemp = maxTemp2;
				}
				if (minTemp1 > minTemp2) {
					minTemp = maxTemp2;
				} else {
					minTemp = minTemp1;
				}

				CzStation list1 = new CzStation();
				list1.setId(stationid);
				list1.setName(r1.getStationname().trim());
				list1.setDate(ybDate.AddDays(index).toDateString());
				list1.setLon(r1.getLongitude().toString());
				list1.setLat(r1.getLatitude().toString());
				list1.setPic1(WebCtrlData.WeatherNameToPicPath(weather1));
				list1.setPic2(WebCtrlData.WeatherNameToPicPath(weather2));
				list1.setWeather1(weather1);
				list1.setWeather2(weather2);
				list1.setMaxTemp(String.valueOf(maxTemp));
				list1.setMinTemp(String.valueOf(minTemp));
				list1.setWindV(windV);
				list1.setWindD(windD);
				result[index] = list1;
				index++;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@Override
	public TourInfo getTourWeather(String tourName, String sc, String date,HttpServletRequest request) {
		TourXYInfo tourXYInfo = getTourXYInfo(tourName);

		TourStaInfo staInfo = new TourStaInfo();
		staInfo = getTourInfo(tourName,request);
		CzStation[] ybList = new CzStation[]{};

		SmallStation skInfo = new SmallStation();
		skInfo = getSKInfoList(staInfo.getId(), "2");//获取旅游天气tour_smallcale
		if (skInfo.getName() != null)
			ybList = getTourInfoList(skInfo.getTime().split(" ")[0] + " 00:00:00", sc, staInfo.getId());
		ZhishuInfo[] zhishu = getZhiShuInfo1(staInfo.getId(), "");
		TourInfo tourInfo = new TourInfo();
		TourStaInfo tourStaInfo = new TourStaInfo();
		tourStaInfo.setId(staInfo.getId());
		tourStaInfo.setName(staInfo.getName());
		tourStaInfo.setImgPath(staInfo.getImgPath());
		tourStaInfo.setLon(tourXYInfo.getX());
		tourStaInfo.setLat(tourXYInfo.getY());
		tourInfo.setTourStaInfo(tourStaInfo);
		tourInfo.setCounty(staInfo.getCounty());
		tourInfo.setSkInfo(skInfo);
		tourInfo.setForecast(ybList);
		tourInfo.setZhishuList(zhishu);
		tourInfo.setWaringInfo(getWarning(DbConfig.CITY));
		return tourInfo;
	}

	@Override
	public TourStaInfo getTourInfo(String tourName,HttpServletRequest request) {
		String result = "";
		TourStaInfo tour = new TourStaInfo();
		HashMap<String, String> tourStaList = CommonDao.tourStaList;
		String tourId = tourStaList.get(tourName.trim());
		try {
			RequestDataBySelect dataBySelect = new RequestDataBySelect();
			dataBySelect.setColumns(new String[]{"text,areaname,grade"});
			dataBySelect.setParam("StationID='" + tourId + "'");
			Map<String, String> map = new HashMap<String, String>();
			map.put("param", JsonUtil.object2Json(dataBySelect));
			map.put("method", "tour_stations");
			map.put("sqlType", "select");
			map.put("advCode", DbConfig.advCode);
			result = pc.processRequest(map);
			if (result.equals("")) {
				result = "[]";
			}

			List<tour_stations> tour_stations = new ArrayList<tour_stations>();
			tour_stations = JsonUtil.jsonStr2TypeReference(result, new TypeReference<List<tour_stations>>() {
			});
			for (tour_stations t : tour_stations) {
				tour.setText(t.getText());
				tour.setImgPath(t.getImagepath());
				tour.setName(t.getAreaname());
				tour.setLevel(t.getGrade());
			}

			tour.setId(tourId);
			tour.setName(tourName);


			String serviceFilePath = "";
			// 下载
			String fileName = tourId+new DateTime().toString();
			String path = request.getContextPath();
			String basePath = DbConfig.IP + path
					+ "/Temp/Tour/";
			String serviceUrl = basePath + fileName;
			String urlpath ;
			if (operatingSystem.equals("Windows")){
				 urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Tour\\";
			}else {
				urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/Tour/";
			}

			serviceFilePath = urlpath + fileName;// 服务器文件
			FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
			FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
			// 如果目录中不存在文件，下载雷达文件到temp目录
			File serviceFile = new File(serviceFilePath);// 服务器文件
			if (!serviceFile.exists()) {// 把文件上传到服务器
				Map<String, Object> queryMap = new HashMap<String, Object>();
				queryMap.put("stationid", tourId+"");
				queryMap.put("advCode", DbConfig.advCode);
				queryMap.put("collectionName", "image_file");
				byte[] data = ms.selectData(queryMap);
				if (data == null) {
					serviceFilePath = "";
				} else {
					FileUtil.bytesToFile(data, serviceFilePath);
				}
			}
			if (!serviceFilePath.equals("")) {
				serviceFilePath = serviceUrl;
			}

			String file = serviceFilePath;
			tour.setImgPath(file);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return tour;
	}

	@Override
	public TourStaInfo getActImgStaInfo(String name, String type,HttpServletRequest request) {
		if ("TourSta".equals(type)) {
			return getTourInfo(name,request);
		} else {
			TourStaInfo tour = new TourStaInfo();
			try {
				// 经度|纬度|高程|简介|图片地址|所属县区
				// 获取景点id根据景点名称
				String strSql = String.format(
						"select stationid as id,stationName as name,longitude as lon,latitude as lat,altitude as alti,text,areaname as county from tour_stations where stationname ='%s'",
						name);
				//初始化旅游景点
				tour = PGUtil.getBean(DbConfig.pg_url + DbConfig.zyConn, DbConfig.pg_userName, DbConfig.pg_pwd, strSql,
						TourStaInfo.class);
				String imgpath = DbConfig.downloadUrl + "stationid=" + tour.getId() + "&collectionName=image_file";
				tour.setImgPath(imgpath);
				;
			} catch (Exception e) {
				e.printStackTrace();
			}
			return tour;
		}
	}

	@Override
	public WarningInfo[] getWarning(String city) {
		String result = "";
		List<WarningInfo> resultList = new ArrayList<WarningInfo>();
		try {
			DateTime date = DateTime.now().AddHours(-24);//
			// 从预警信号监控表中读取信息

			RequestDataBySelect dataBySelect = new RequestDataBySelect();
			dataBySelect.setColumns(new String[]{"id,Area, Type,Color,City,County,Standard,DefenseGuide,AnnouncedTime"});
			dataBySelect.setParam("bFree=0 and AnnouncedTime >'" + date.toDateTimeString() + "' and (description  like ('%" + DbConfig.CITY + "%')) and 1=1");//+"' and County like '%"+county+"%'"
			dataBySelect.setSort(new String[]{"AnnouncedTime desc"});
			dataBySelect.setLimit(1);
			Map<String, String> map = new HashMap<String, String>();
			map.put("param", JsonUtil.object2Json(dataBySelect));
			map.put("method", "warn_signal_info");
			map.put("sqlType", "select");
			result = pc.processRequest(map);
			if (result.equals("")) {
				result = "[]";
			}
			resultList = JsonUtil.jsonStr2TypeReference(result, new TypeReference<List<WarningInfo>>() {
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
		WarningInfo[] warningInfos = resultList.toArray(new WarningInfo[resultList.size()]);
		return warningInfos;
	}

	@Override
	public Object getWarningById(String warningId) {
		String result = "";
		WarningInfo warningInfo = new WarningInfo();
		try {
			RequestDataBySelect dataBySelect = new RequestDataBySelect();
			dataBySelect.setColumns(new String[]{"Area,Type,Color,City,County,Standard,DefenseGuide,AnnouncedTime"});
			dataBySelect.setSort(new String[]{"AnnouncedTime DESC"});
			if (warningId != null && !warningId.equals("") && !warningId.equals("undefined")) {
				dataBySelect.setParam("id='" + warningId + "'");
			}
			dataBySelect.setLimit(1);
			Map<String, String> map = new HashMap<String, String>();
			map.put("param", JsonUtil.object2Json(dataBySelect));
			map.put("method", "warn_signal_info");
			map.put("sqlType", "select");
			result = pc.processRequest(map);
			if (result.equals("")) {
				result = "[]";
			}
			List<WarningInfo> list = new ArrayList<WarningInfo>();
			list = JsonUtil.jsonStr2TypeReference(result, new TypeReference<List<WarningInfo>>() {
			});

			for (WarningInfo w : list) {
				warningInfo.setArea(w.getArea().toString());
				warningInfo.setType(w.getType());
				warningInfo.setColor(w.getColor());
				warningInfo.setCity(w.getCity());
				warningInfo.setCounty(w.getCounty());
				warningInfo.setStandard(w.getStandard());
				warningInfo.setdefenseguide(w.getdefenseguide());
				warningInfo.setTime(new DateTime(w.getannouncedtime()).toDateTimeString("yyyy-MM-dd"));
			}

		} catch (Exception e) {

		}

		return warningInfo;
	}

	@Override
	public ZhishuInfo[] getZhiShuInfo1(String tourId, String countyName) {
		String result = "";
		ZhishuInfo[] resultList = null;
		Map<String, String> zs = DbConfig.getlyZhiShuType();
		String countyId = "";
		if (!StringUtil.IsNullOrEmpty(countyName) && StringUtil.IsNullOrEmpty(tourId)) {
			HashMap<String, String> stationList = CommonDao.stationList;// 初始化站点
			if (stationList.containsKey(countyName)) {
				countyId = stationList.get(countyName).toString();
			} else {
				countyId = DbConfig.STATIONID;
			}
		} else if (!StringUtil.IsNullOrEmpty(tourId)) {
			countyId = tourId.toString();
		}

		try {
			RequestDataBySelect dataBySelect = new RequestDataBySelect();
			dataBySelect.setColumns(new String[]{"max(DateChar) as DateChar"});
			dataBySelect.setParam("CityID='" + countyId + "'");
			Map<String, String> map = new HashMap<String, String>();
			map.put("param", JsonUtil.object2Json(dataBySelect));
			map.put("method", "zhishu");
			map.put("sqlType", "select");
			map.put("advCode", DbConfig.advCode);
			result = pc.processRequest(map);
			if (result.equals("")) {
				result = "[]";
			}
			List<zhishu> list = new ArrayList<zhishu>();
			list = JsonUtil.jsonStr2TypeReference(result, new TypeReference<List<zhishu>>() {
			});
			RequestDataBySelect dataBySelect1 = new RequestDataBySelect();
			SimpleDateFormat simpleFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			StringBuilder strWhere = new StringBuilder();
			int whereCount = 0;
			if(!StringUtil.IsNullOrEmpty(countyId)){
				whereCount++;
				strWhere.append(" CityID= '" + countyId + "'");
			}
			if(list!=null && list.get(0).getDatechar() != null){
				strWhere.append(" and DateChar='" + simpleFormatter.format(list.get(0).getDatechar()) + "' ");
			}
			if (whereCount == 0 && !com.dmgis.qxfw.dataservice.commonservice.utils.StringUtil.IsNullOrEmpty(strWhere.toString())) {
				strWhere = strWhere.replace(0, 4, "");
			}
			dataBySelect1.setParam(strWhere.toString());
			Map<String, String> map1 = new HashMap<String, String>();
			map1.put("param", JsonUtil.object2Json(dataBySelect1));
			map1.put("method", "zhishu");
			map1.put("sqlType", "select");
			map1.put("advCode", DbConfig.advCode);
			String result1 = "";
			result1 = pc.processRequest(map1);
			if (result.equals("")) {
				result = "[]";
			}

			resultList = new ZhishuInfo[zs.size()];

			List<Map<String, Object>> list1 = new ArrayList<Map<String, Object>>();
			list1 = JsonUtil.jsonStr2TypeReference(result1, new TypeReference<List<Map<String, Object>>>() {
			});

			for (Map<String, Object> z : list1) {
				Iterator<Map.Entry<String, String>> iterator = zs.entrySet().iterator();
				Map.Entry<String, String> entry;
				int i = 0;
				while (iterator.hasNext()) {
					ZhishuInfo zhishuInfo = new ZhishuInfo();
					entry = iterator.next();
					String key = entry.getKey();
					zhishuInfo.setType(entry.getValue());
					String grade = z.get(key + "grade").toString();
					String text = z.get(key + "text").toString();

					if ("NULL".equals(grade) || "NULL".equals(text)) {
						zhishuInfo.setGrade("无");
						zhishuInfo.setText("无");
					} else {
						zhishuInfo.setGrade(grade);
						zhishuInfo.setText(text);
					}
					resultList[i] = zhishuInfo;
					i++;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultList;
	}

	@SuppressWarnings("unchecked")
	@Override
	public ZhishuInfo[] getZhiShuInfo2(String name, String countyName) {
		// 晨练指数 舒适度 穿衣指数 感冒指数 晾晒指数 旅游指数 紫外线强度 洗车指数 运动指数 约会指数 雨伞指数
		String[] zhishuSelect = new String[]{"舒适度", "穿衣指数", "旅游指数", "感冒指数", "紫外线强度", "雨伞指数"};
		String posturl = "http://wthrcdn.etouch.cn/WeatherApi?city=" + countyName;
		ZhishuInfo[] resultList = new ZhishuInfo[zhishuSelect.length];
		int index = 0;
		try {
			HttpRequest request = HttpRequest.get(posturl, true);// 注意，一定要把true加上，强制编码，很坑
			request.acceptGzipEncoding().uncompress(true);
			String uncompressed = request.body();
			InputSource in = new InputSource(new StringReader(uncompressed));
			in.setEncoding("UTF-8");
			SAXReader reader = new SAXReader();
			Document document = reader.read(in);
			Element root = document.getRootElement();
			// List list= root.selectNodes("/zhishus");
			// List<Element> elements = root.elements("zhishus");
			Element zhishus = root.element("zhishus");
			List<Element> elements = zhishus.elements("zhishu");
			for (Iterator<Element> it = elements.iterator(); it.hasNext(); ) {
				Element element = it.next();// 获取zhishu信息
				String zsName = element.element("name").getTextTrim();

				for (String type : zhishuSelect) {
					if (type.equals(zsName)) {
						ZhishuInfo zsInfo = new ZhishuInfo();
						String zsValue = element.element("value").getTextTrim();
						String zsDetail = element.element("detail").getTextTrim();
						zsInfo.setType(type);
						zsInfo.setGrade(zsValue);
						zsInfo.setText(zsDetail);
						resultList[index] = zsInfo;
						index++;
						break;
					}
				}
			}

		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return resultList;
	}

	@Override
	public List<String> getAllStationCHN() {
		List<String> resultList = new ArrayList<String>();
		try {
			String strSql = String.format("SELECT distinct Name,Longitude,Latitude FROM County where Name is not null");
			List<Map<String, Object>> dt = PGUtil.getResultSet2MapArr(DbConfig.pg_url + DbConfig.qxConn,
					DbConfig.pg_userName, DbConfig.pg_pwd, strSql);
			// DataTable dt = PGHelper.ExecuteDataSet(DbConfig.qx_conn,
			// strSql).Tables[0];
			strSql = String.format("SELECT distinct Name,X,Y FROM City");
			List<Map<String, Object>> dt1 = PGUtil.getResultSet2MapArr(DbConfig.pg_url + DbConfig.qxConn,
					DbConfig.pg_userName, DbConfig.pg_pwd, strSql);
			strSql = String.format("SELECT distinct StationName,Longitude,Latitude FROM tour_stations");
			List<Map<String, Object>> dt2 = PGUtil.getResultSet2MapArr(DbConfig.pg_url + DbConfig.zyConn,
					DbConfig.pg_userName, DbConfig.pg_pwd, strSql);
			for (Map<String, Object> map1 : dt1) {
				try {
					if (map1.get("name").toString().indexOf("市") > 0) {
						resultList.add(map1.get("name").toString());
						// arr.Add(r["Name"].ToString().Trim() + "|" +
						// r["X"].ToString().Trim() + "|" +
						// r["Y"].ToString().Trim());
					} else {
						resultList.add(map1.get("name").toString().trim() + "市");
						// arr.Add(r["Name"].ToString().Trim() + "市" + "|" +
						// r["X"].ToString().Trim() + "|" +
						// r["Y"].ToString().Trim());
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			for (Map<String, Object> map : dt) {
				try {
					resultList.add(map.get("name").toString());
					// arr.Add(r["Name"].ToString().Trim() + "|" +
					// r["Longitude"].ToString().Trim() + "|" +
					// r["Latitude"].ToString().Trim());
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
			for (Map<String, Object> map2 : dt2) {
				try {
					resultList.add(map2.get("stationname").toString());
					// 景区添加标识符@2，用来区别景区和城市
					// arr.Add(r["StationName"].ToString().Trim() + "@" + "|" +
					// r["Longitude"].ToString().Trim() + "|" +
					// r["Latitude"].ToString().Trim());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			// object[] objs = Common.webClient.GetStationCHN();
			// foreach (object obj in objs)
			// {
			// String name = obj.ToString().Split('|')[0];//第一个值
			// resultList.Add(name);
			// }
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultList;
	}

	@Override
	public List<XYInfo> getAllStationXYInfoCHN() {
		List<XYInfo> resultList = new ArrayList<XYInfo>();
		try {
			String strSql = String
					.format("SELECT distinct Name,Longitude as x,Latitude as y FROM County where Name is not null");
			List<Map<String, Object>> dt = PGUtil.getResultSet2MapArr(DbConfig.pg_url + DbConfig.qxConn,
					DbConfig.pg_userName, DbConfig.pg_pwd, strSql);
			// DataTable dt = PGHelper.ExecuteDataSet(DbConfig.qx_conn,
			// strSql).Tables[0];
			strSql = String.format("SELECT distinct Name,X,Y FROM City");
			List<Map<String, Object>> dt1 = PGUtil.getResultSet2MapArr(DbConfig.pg_url + DbConfig.qxConn,
					DbConfig.pg_userName, DbConfig.pg_pwd, strSql);
			strSql = String
					.format("SELECT distinct StationName as name,Longitude as x,Latitude as y FROM tour_stations");
			List<Map<String, Object>> dt2 = PGUtil.getResultSet2MapArr(DbConfig.pg_url + DbConfig.zyConn,
					DbConfig.pg_userName, DbConfig.pg_pwd, strSql);
			for (Map<String, Object> map1 : dt1) {
				try {
					XYInfo xyInfo = new XYInfo();
					if (map1.get("name").toString().indexOf("市") > 0) {
						xyInfo.setCity(map1.get("name").toString());
						xyInfo.setX(map1.get("x").toString());
						xyInfo.setY(map1.get("y").toString());
					} else {
						xyInfo.setCity(map1.get("name").toString().trim() + "市");
						xyInfo.setX(map1.get("x").toString());
						xyInfo.setY(map1.get("y").toString());
					}
					resultList.add(xyInfo);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			for (Map<String, Object> map : dt) {
				XYInfo xyInfo = new XYInfo();
				try {
					xyInfo.setCity(map.get("name").toString());
					xyInfo.setX(map.get("x").toString());
					xyInfo.setY(map.get("y").toString());
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
			for (Map<String, Object> map2 : dt2) {
				XYInfo xyInfo = new XYInfo();
				try {
					xyInfo.setCity(map2.get("name").toString() + "@");
					xyInfo.setX(map2.get("x").toString());
					xyInfo.setY(map2.get("y").toString());
					resultList.add(xyInfo);
					// 景区添加标识符@，用来区别景区和城市
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultList;
	}

	@Override
	public XYInfo getXYInfo(String stationName) {
		String result = "";
		List<XYInfo> list = new ArrayList<XYInfo>();
		try {

			RequestDataBySelect dataBySelect = new RequestDataBySelect();
			dataBySelect.setColumns(new String[]{" NAME,X ,Y"});
			dataBySelect.setParam("name like '%" + StringUtil.trimEnd(stationName, '市') + "%'");
			dataBySelect.setLimit(1);
			Map<String, String> map = new HashMap<String, String>();
			map.put("param", JsonUtil.object2Json(dataBySelect));
			map.put("method", "City");
			map.put("sqlType", "select");
			result = pc.processRequest(map);
			if (result.equals("")) {
				result = "[]";
			}
			List<city> citylist = JsonUtil.jsonStr2TypeReference(result, new TypeReference<List<city>>() {
			});
			if (citylist != null && citylist.size() > 0) {
				for (city c : citylist) {
					XYInfo xyinfo = new XYInfo();
					xyinfo.setCity(c.getName());
					xyinfo.setX(c.getX().toString());
					xyinfo.setY(c.getY().toString());
					list.add(xyinfo);
				}
			}
			if (list.size() == 0) {
				RequestDataBySelect dataBySelect1 = new RequestDataBySelect();
				dataBySelect1.setColumns(new String[]{" City,Longitude,Latitude"});
				dataBySelect1.setParam("name like '%" + stationName + "%'");
				dataBySelect1.setLimit(1);
				Map<String, String> map1 = new HashMap<String, String>();
				map1.put("param", JsonUtil.object2Json(dataBySelect1));
				map1.put("method", "County");
				map1.put("sqlType", "select");
				result = pc.processRequest(map1);
				if (result.equals("")) {
					result = "[]";
				}
				List<county> countylist = JsonUtil.jsonStr2TypeReference(result, new TypeReference<List<county>>() {
				});

				if (countylist != null && countylist.size() > 0) {
					for (county c : countylist) {
						XYInfo xyinfo = new XYInfo();
						xyinfo.setCity(c.getCity());
						xyinfo.setX(c.getLongitude().toString());
						xyinfo.setY(c.getLatitude().toString());
						list.add(xyinfo);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list.get(0);
	}

	@Override
	public String GetNearestStaIdByXY(String lon, String lat, String city) {
		String result = "";
		String strSqlParam = "City";
		String[] ProvinceCity = new String[]{"北京", "上海", "重庆", "天津"};
		for (String strCity : ProvinceCity) {
			if (city.indexOf(strCity) >= 0) {
				// 以省作为参数
				strSqlParam = "Province";
				break;
			}
		}
		try {
			double distance = 0;
			String stationId = "";
			String strSql = "";
			if (!city.equals(DbConfig.COUNTY)) {
				RequestDataBySelect dataBySelect = new RequestDataBySelect();
				dataBySelect.setColumns(new String[]{"StationID,StationName ,Longitude ,Latitude"});
				dataBySelect.setParam(strSqlParam + " like '%" + city + "%'");
				Map<String, String> map = new HashMap<String, String>();
				map.put("param", JsonUtil.object2Json(dataBySelect));
				map.put("method", "STA_INFO_SURF_CHN_N");
				map.put("sqlType", "select");
				result = pc.processRequest(map);
				if (result.equals("")) {
					result = "[]";
				}
			} else {
				RequestDataBySelect dataBySelect = new RequestDataBySelect();
				dataBySelect.setColumns(new String[]{"StationID,StationName ,Longitude ,Latitude"});
				dataBySelect.setParam(strSqlParam + " like '%" + city + "%' and stationname='"+DbConfig.STATIONNAME+"'");
				Map<String, String> map = new HashMap<String, String>();
				map.put("param", JsonUtil.object2Json(dataBySelect));
				map.put("method", "STA_INFO_SURF_CHN_N");
				map.put("sqlType", "select");
				result = pc.processRequest(map);
				if (result.equals("")) {
					result = "[]";
				}
			}
			if (city == "") {
				RequestDataBySelect dataBySelect = new RequestDataBySelect();
				dataBySelect.setColumns(new String[]{"StationID,StationName ,Longitude ,Latitude"});
				Map<String, String> map = new HashMap<String, String>();
				map.put("param", JsonUtil.object2Json(dataBySelect));
				map.put("method", "STA_INFO_SURF_CHN_N");
				map.put("sqlType", "select");
				result = pc.processRequest(map);
				if (result.equals("")) {
					result = "[]";
				}
			}

			List<HashMap<String, Object>> list = JsonUtil.jsonStr2TypeReference(result, new TypeReference<List<HashMap<String, Object>>>() {
			});

			for (HashMap<String, Object> map : list) {
				double X = Double.parseDouble(lon) - (Double) (map.get("longitude"));
				double Y = Double.parseDouble(lat) - (Double) (map.get("latitude"));
				double tempDistance = Math.sqrt(Math.pow(X, 2) + Math.pow(Y, 2));
				if (tempDistance < distance || distance == 0) {
					distance = tempDistance;
					stationId = map.get("stationid").toString().trim();
				}
			}
			if (list.size() == 0) {
				String province = CommonDao.getGoverInfo(city).split("\\|")[1];
				RequestDataBySelect dataBySelect = new RequestDataBySelect();
				dataBySelect.setColumns(new String[]{"StationID,StationName ,Longitude ,Latitude"});
				dataBySelect.setParam("Province like '%" + province.substring(0, 2) + "%'");
				Map<String, String> map = new HashMap<String, String>();
				map.put("param", JsonUtil.object2Json(dataBySelect));
				map.put("method", "STA_INFO_SURF_CHN_N");
				map.put("sqlType", "select");
				result = pc.processRequest(map);
				if (result.equals("")) {
					result = "[]";
				}
				List<HashMap<String, Object>> list1 = JsonUtil.jsonStr2TypeReference(result, new TypeReference<List<HashMap<String, Object>>>() {
				});


				for (HashMap<String, Object> map1 : list1) {
					double X = Double.parseDouble(lon) - (Double) (map1.get("longitude"));
					double Y = Double.parseDouble(lat) - (Double) (map1.get("latitude"));
					double tempDistance = Math.sqrt(Math.pow(X, 2) + Math.pow(Y, 2));
					if (tempDistance < distance || distance == 0) {
						distance = tempDistance;
						stationId = map.get("stationid").toString().trim();
					}
				}
			}
			result = stationId;
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return result;
	}

	@Override
	public String GetNcNearestStaIdByXY(String lon, String lat) {
		String result = "";
		double distance = 0;
		try {
			RequestDataBySelect dataBySelect = new RequestDataBySelect();
			dataBySelect.setColumns(new String[]{"StationID ,StationName ,Longitude ,Latitude"});
			Map<String, String> map = new HashMap<String, String>();
			map.put("param", JsonUtil.object2Json(dataBySelect));
			map.put("method", "STA_INFO_SURF_CHN_N");
			map.put("sqlType", "select");
			result = pc.processRequest(map);
			if (result.equals("")) {
				result = "[]";
			}
			List<HashMap<String, Object>> lists = JsonUtil.jsonStr2TypeReference(result, new TypeReference<List<HashMap<String, Object>>>() {
			});
			for (Map<String, Object> ls : lists) {
				double X = Double.parseDouble(lon) - (Double) (ls.get("longitude"));
				double Y = Double.parseDouble(lat) - (Double) (ls.get("latitude"));
				double tempDistance = Math.sqrt(Math.pow(X, 2) + Math.pow(Y, 2));
				if (tempDistance < distance || distance == 0) {
					distance = tempDistance;
					result = map.get("stationid").toString().trim();
				}
			}
		} catch (Exception e) {
			//TODO
		}
		return result;
	}

	@Override
	public String GetNearestCityNameByXY(String lon, String lat, List<XYInfo> arr) {
		String cityName = "";
		double distance = 0;
		for (XYInfo xyInfo : arr) {
			double X = Double.parseDouble(lon) - Double.parseDouble(xyInfo.getX());
			double Y = Double.parseDouble(lat) - Double.parseDouble(xyInfo.getY());
			double tempDistance = Math.sqrt(Math.pow(X, 2) + Math.pow(Y, 2));
			if (tempDistance < distance || distance == 0) {
				distance = tempDistance;
				cityName = xyInfo.getCity();
			}
		}
		return cityName;
	}

	@Override
	public ArrayList<Object> getAllTourStaInfo() {
		String result = "";
		ArrayList<Object> arr = new ArrayList<Object>();
		try {
			List<TourStaInfo> resultList = new ArrayList<TourStaInfo>();
			List<tour_stations> resultList1 = new ArrayList<tour_stations>();
			RequestDataBySelect dataBySelect = new RequestDataBySelect();
			dataBySelect.setColumns(new String[]{"StationID,StationName,Longitude,Latitude,Grade"});
			HashMap<String, String> map = new HashMap<>();
			map.put("param", JsonUtil.object2Json(dataBySelect));
			map.put("method", "tour_stations");
			map.put("sqlType", "select");
			map.put("advCode", DbConfig.advCode);
			result = pc.processRequest(map);
			resultList1 = JsonUtil.jsonStr2TypeReference(result, new TypeReference<List<tour_stations>>() {
			});

			for (tour_stations tourStaInfo : resultList1) {
				if (StringUtil.IsNullOrEmpty(tourStaInfo.getGrade()))
					continue;
				String grade = tourStaInfo.getGrade().trim();
				tourStaInfo.setGrade(grade.length() + "A");
				TourStaInfo tourStaInf = new TourStaInfo();
				tourStaInf.setLevel(grade.length() + "A");
				tourStaInf.setName(tourStaInfo.getStationname());
				tourStaInf.setId(tourStaInfo.getStationid());
				tourStaInf.setLon(tourStaInfo.getLongitude().toString());
				tourStaInf.setLat(tourStaInfo.getLatitude().toString());
				resultList.add(tourStaInf);
			}
			arr.add(resultList);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return arr;
	}

	@Override
	public TourXYInfo getTourXYInfo(String stationName) {
		String result = "";
		//没问题
		TourXYInfo list = new TourXYInfo();
		try {
			RequestDataBySelect dataBySelect = new RequestDataBySelect();
			dataBySelect.setColumns(new String[]{"StationID,stationname,Longitude,Latitude,AreaName"});
			dataBySelect.setParam("StationName like '%" + stationName + "%'");
			dataBySelect.setLimit(1);
			Map<String, String> map = new HashMap<String, String>();
			map.put("param", JsonUtil.object2Json(dataBySelect));
			map.put("method", "tour_stations");
			map.put("advCode", DbConfig.advCode);
			map.put("sqlType", "select");
			result = pc.processRequest(map);
			if (result.equals("")) {
				result = "[]";
			}
			List<tour_stations> tour_stations = new ArrayList<tour_stations>();
			tour_stations = JsonUtil.jsonStr2TypeReference(result, new TypeReference<List<tour_stations>>() {
			});
			for (tour_stations t : tour_stations) {
				list.setStationid(t.getStationid());
				list.setStationName(t.getStationname());
				list.setX(t.getLongitude().toString());
				list.setY(t.getLatitude().toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public String GetNearestStaNameByTourXY(String lon, String lat, String city) {
		String result = "";
		try {
			double distance = 0;
			String stationId = "";
			String strWhere = String.format("where County like '%%%s%%'", city);
			// 常德开头
			if (city.indexOf(DbConfig.CITY) == 0) {
				strWhere = String.format("where City like '%%%s%%'", city);
			}
			String strSql = String
					.format("SELECT StationID ,StationName ,Longitude ,Latitude FROM smallscale_station %s", strWhere);
			List<Map<String, Object>> dt = PGUtil.getResultSet2MapArr(DbConfig.pg_url + DbConfig.qxConn,
					DbConfig.pg_userName, DbConfig.pg_pwd, strSql);
			for (Map<String, Object> map : dt) {
				double X = Double.parseDouble(lon) - (Double) (map.get("longitude"));
				double Y = Double.parseDouble(lat) - (Double) (map.get("latitude"));
				double tempDistance = Math.sqrt(Math.pow(X, 2) + Math.pow(Y, 2));
				if (tempDistance < distance || distance == 0) {
					distance = tempDistance;
					stationId = map.get("stationid").toString().trim();
				}
			}
			result = stationId;
		} catch (Exception ex) {

			throw ex;
		}
		return result;
	}

	@Override
	public ContourImg getSKDZTList(String element, String url, String localPath,String date) {
		String el = element;
		String ele = el;
		String collectType = "";
		String description = "";
		String timeType = "1";
		ContourImg result = new ContourImg();
		try {
			if (el.contains("雨")) {
				collectType = "rain";
				if (el.equals("雨量")) {
					timeType = "1";
				} else if (el.contains("三")) {
					timeType = "3";
				} else if (el.contains("六")) {
					timeType = "6";
				} else if (el.contains("十二")) {
					timeType = "12";
				} else if (el.contains("二十四")) {
					timeType = "24";
				} else {
					timeType = "1";
				}
			}

			if (el.contains("温")) {

				collectType = "temp";
				if (el.contains("平均")) {
					ele = "温度";
				} else if (el.contains("最高")) {
					ele = "最高温";
				} else if (el.contains("最低")) {
					ele = "最低温";
				}

			}
			if (el.contains("风")) {
				if (el.contains("整点")) {
					ele = "风速";
				} else if (el.contains("极大")) {
					ele = "极大风速";
				}
				collectType = "wind";
			}
			if (el.contains("湿")) {
				if (el.equals("相对湿度")) {
					ele = "湿度";
				} else if (el.equals("最小相对湿度")) {
					ele = "最小相对湿度";
				}
				collectType = "humid";
			}
			if (el.contains("气")) {
				collectType = "press";
			}
			if (el.contains("能见度")){
				collectType = "vis";
			}
			// 类型不为空
			if (!collectType.equals("")) {
				int index = 0;
				ContourImg contourImg = new ContourImg();
				int i = 0;
				DateTime dateTime = DateTime.parseDateTime(DateTime.now().toDateTimeString());//  括号里面原来内容 2019-05-19 12:00:00
				for (i = 0; i < 3; i++) {
					dateTime = dateTime.AddHours(-i);
					String fileName = el + dateTime.toDateTimeString("yyyyMMddHH0000") + ".jpg";
					File file = new File(localPath + fileName);
					if (!file.exists()) {
						// 从mongdb获取图片
						Map<String, Object> map1 = new HashMap<String, Object>();
						map1.put("type", ele);
						map1.put("datechar", dateTime.toDateTimeString("yyyy-MM-dd HH:00:00"));
						//map1.put("datechar", date);
						map1.put("collectionName", "sk_" + collectType + "_jpg_file");
						//map1.put("advCode", DbConfig.advCode);
						byte[] data = ms.selectData(map1);
						if (data != null) {
							contourImg.setType(el);
							contourImg.setName(url + fileName);
							// description = getSKDZTQuery(collectType, el, timeType, dateTime);
							// contourImg.setDescription(description);
							result = contourImg;
							FileUtil.bytesToFile(data, localPath + fileName);
							index++;
							break;
						} else {
							contourImg.setType(el);
							contourImg.setName("images/tourinfo/none.jpg");
							contourImg.setDescription("");
							result = contourImg;
						}
					} else {
						contourImg.setType(el);
						contourImg.setName(url + fileName);
						// description = getSKDZTQuery(collectType, el, timeType, dateTime);
						// contourImg.setDescription(description);
						result = contourImg;
						index++;
						break;
					}
				}
				if (i == 3) {
					result = contourImg;
					index++;
				}
			}
			// }
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}

	private String getSKDZTQuery(String Element, String eleType, String timeType, DateTime endTime) throws ParseException {
		String result = "";
		String strStartDate = "";
		String strEndDate = endTime.toDateTimeString();
		String elemType = eleType;
		String type = "";
		SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日HH时");
		if (timeType.equals("1")) {
			strStartDate = endTime.AddHours(-1).toDateTimeString();
		} else if (timeType.equals("3")) {
			strStartDate = endTime.AddHours(-3).toDateTimeString();
		} else if (timeType.equals("6")) {
			strStartDate = endTime.AddHours(-6).toDateTimeString();
		} else if (timeType.equals("12")) {
			strStartDate = endTime.AddHours(-12).toDateTimeString();
		} else if (timeType.equals("24")) {
			strStartDate = endTime.AddHours(-24).toDateTimeString();
		} else {
			strStartDate = endTime.AddHours(-1).toDateTimeString();
		}
		Date startDate = DateTime.parseDateTime(strStartDate).toDate();
		strStartDate = format.format(startDate);

		Date endDate = DateTime.parseDateTime(strEndDate).toDate();
		strEndDate = format.format(endDate);
		if (elemType.contains("雨")) {
			type = "sum";
		}
		if (elemType.contains("温")) {
			if (eleType.contains(("最高"))) {
				type = "max";
			} else if (eleType.contains(("最低"))) {
				type = "min";
			} else {
				type = "avg";
			}
		}
		if (elemType.contains("风")) {
			if (eleType.contains(("极大"))) {
				type = "max";
			} else {
				type = "avg";
			}
		}
		if (elemType.contains("湿")) {
			if (elemType.equals("相对湿度")) {
				type = "avg";
			} else {
				type = "min";
			}
		}
		if (elemType.contains("风")) {
			if (elemType.equals("整点风")) {
				type = "avg";
			} else {
				type = "max";
			}
		}
		List<String> countys = new ArrayList<>();
		countys.add(DbConfig.CITY); //常德
		ActualElemQuery elemQuery = new ActualElemQuery();
		elemQuery.setElement(Element);
		elemQuery.setStartDate(startDate);
		elemQuery.setEndDate(endDate);
		elemQuery.setType(type);
		elemQuery.setCountys(countys);
		List<ActualData> resultList = qxElementQuery(elemQuery);
		if (elemType.contains("雨")) {
			String RainDisp = "";
			double Total = 0.0;
			int noRain = 0;
			int littleRain = 0;
			int middleRain = 0;
			int bigRain = 0;
			int hervyRain = 0;
			int hardRain = 0;
			int veryHardRain = 0;
			if (resultList.size() > 0) {


				for (int i = 0; i < resultList.size(); i++) {

					double rain = resultList.get(i).getRain();
					if (rain >= 200) {
						veryHardRain++;
					} else if (rain >= 100) {
						hardRain++;

					} else if (rain >= 50) {
						hervyRain++;
					} else if (rain >= 25) {
						bigRain++;
					} else if (rain >= 10) {
						middleRain++;
					} else if (rain > 0) {
						littleRain++;
					} else {
						noRain++;
					}
				}
				if (veryHardRain != 0) {
					if (!strStartDate.equals(strEndDate)) {
						RainDisp = String.format("根据监测显示，%s至%s,据全市%s个区域自动气象站资料统计，有%s站小雨，%s站中雨，%s站大雨，%s站暴雨,%s站大暴雨，%s站特大暴雨。其中最大降雨量为%smm(%s)", strStartDate, strEndDate, resultList.size(), littleRain, middleRain, bigRain, hervyRain, hardRain, veryHardRain, resultList.get(0).getRain(), resultList.get(0).getStationName());

					} else {
						RainDisp = String.format("根据监测显示，%s,据全市%s个区域自动气象站资料统计，有%s站小雨，%s站中雨，%s站大雨，%s站暴雨,%s站大暴雨，%s站特大暴雨。其中最大降雨量为%smm(%s)", strStartDate, resultList.size(), littleRain, middleRain, bigRain, hervyRain, hardRain, veryHardRain, resultList.get(0).getRain(), resultList.get(0).getStationName());
					}
				} else if (hardRain != 0) {
					if (!strStartDate.equals(strEndDate)) {
						RainDisp = String.format("根据监测显示，%s至%s,据全市%s个区域自动气象站资料统计，有%s站小雨，%s站中雨，%s站大雨，%s站暴雨,%s站大暴雨。其中最大降雨量为%smm(%s)", strStartDate, strEndDate, resultList.size(), littleRain, middleRain, bigRain, hervyRain, hardRain, resultList.get(0).getRain(), resultList.get(0).getStationName());

					} else {
						RainDisp = String.format("根据监测显示，%s,据全市%s个区域自动气象站资料统计，有%s站小雨，%s站中雨，%s站大雨，%s站暴雨,%s站大暴雨。其中最大降雨量为%smm(%s)", strStartDate, resultList.size(), littleRain, middleRain, bigRain, hervyRain, hardRain, resultList.get(0).getRain(), resultList.get(0).getStationName());
					}
				} else if (hervyRain != 0) {
					if (!strStartDate.equals(strEndDate)) {
						RainDisp = String.format("根据监测显示，%s至%s,据全市%s个区域自动气象站资料统计，有%s站小雨，%s站中雨，%s站大雨，%s站暴雨。其中最大降雨量为%smm(%s)", strStartDate, strEndDate, resultList.size(), littleRain, middleRain, bigRain, hervyRain, resultList.get(0).getRain(), resultList.get(0).getStationName());

					} else {
						RainDisp = String.format("根据监测显示，%s,据全市%s个区域自动气象站资料统计，有%s站小雨，%s站中雨，%s站大雨，%s站暴雨。其中最大降雨量为%smm(%s)", strStartDate, resultList.size(), littleRain, middleRain, bigRain, hervyRain, resultList.get(0).getRain(), resultList.get(0).getStationName());

					}
				} else if (bigRain != 0) {
					if (!strStartDate.equals(strEndDate)) {
						RainDisp = String.format("根据监测显示，%s至%s,据全市%s个区域自动气象站资料统计，有%s站小雨，%s站中雨，%s站大雨。其中最大降雨量为%smm(%s)", strStartDate, resultList.size(), strEndDate, littleRain, middleRain, bigRain, resultList.get(0).getRain(), resultList.get(0).getStationName());

					} else {
						RainDisp = String.format("根据监测显示，%s,据全市%s个区域自动气象站资料统计，有%s站小雨，%s站中雨，%s站大雨。其中最大降雨量为%smm(%s)", strStartDate, resultList.size(), littleRain, middleRain, bigRain, resultList.get(0).getRain(), resultList.get(0).getStationName());
					}
				} else if (middleRain != 0) {
					if (!strStartDate.equals(strEndDate)) {
						RainDisp = String.format("根据监测显示，%s至%s,据全市%s个区域自动气象站资料统计，有%s站小雨，%s站中雨。其中最大降雨量为%smm(%s)", strStartDate, strEndDate, resultList.size(), littleRain, middleRain, resultList.get(0).getRain(), resultList.get(0).getStationName());

					} else {
						RainDisp = String.format("根据监测显示，%s,据全市%s个区域自动气象站资料统计，有%s站小雨，%s站中雨。其中最大降雨量为%smm(%s)", strStartDate, resultList.size(), littleRain, middleRain, resultList.get(0).getRain(), resultList.get(0).getStationName());

					}
				} else if (littleRain != 0) {
					if (!strStartDate.equals(strEndDate)) {
						RainDisp = String.format("根据监测显示，%s至%s,据全市%s个区域自动气象站资料统计，有%s站小雨。其中最大降雨量为%smm(%s)", strStartDate, strEndDate, resultList.size(), littleRain, resultList.get(0).getRain(), resultList.get(0).getStationName());

					} else {
						RainDisp = String.format("根据监测显示，%s,据全市%s个区域自动气象站资料统计，有%s站小雨。其中最大降雨量为%smm(%s)", strStartDate, resultList.size(), littleRain, resultList.get(0).getRain(), resultList.get(0).getStationName());

					}
				} else {
					if (!strStartDate.equals(strEndDate)) {
						RainDisp = String.format("根据监测显示，%s至%s,据全市%s个区域自动气象站资料统计，有%s站无雨。", strStartDate, strEndDate, resultList.size(), noRain);
					} else {
						RainDisp = String.format("根据监测显示，%s,据全市%s个区域自动气象站资料统计，有%s站无雨。", strStartDate, resultList.size(), noRain);
					}
				}
			}
			result = RainDisp;
		} else if (elemType.contains("温")) {
			String TempDisp = "";
			double Totaltemp = 0;
			String maxSta = "";
			String minSta = "";
			double mintemp = resultList.get(0).getTemp();
			minSta = resultList.get(0).getStationName();
			double maxtemp = resultList.get(resultList.size() - 1).getTemp();
			maxSta = resultList.get(resultList.size() - 1).getStationName();
			double avgtemp = 0;
			int flag = 0;
			for (int i = 0; i < resultList.size(); i++) {
				double temp = resultList.get(i).getTemp();
				if (temp != -65535) {
					flag++;
					Totaltemp = Totaltemp + temp;
				}
			}
			avgtemp = Totaltemp / flag;
			String strTemp = String.format("%.1f", avgtemp);
			avgtemp = Double.valueOf(strTemp);
			//根据监测显示，时间（例如2019年11月19日15时），据全市111个区域自动气象站资料统计，最高温度35℃（XX),最低温度32℃（XX），全市平均温度30℃。
			if (!strStartDate.equals(strEndDate)) {
				TempDisp = String.format("根据监测显示，%s至%s,据全市%s个区域自动气象站资料统计，最高温度%s℃（%s）,最低温度%s℃（%s），全市平均温度%s℃。", strStartDate, strEndDate, resultList.size(), maxtemp, maxSta, mintemp, minSta, avgtemp);

			} else {
				TempDisp = String.format("根据监测显示，%s,据全市%s个区域自动气象站资料统计，最高温度%s℃（%s）,最低温度%s℃（%s），全市平均温度%s℃。", strStartDate, resultList.size(), maxtemp, maxSta, mintemp, minSta, avgtemp);

			}
			result = TempDisp;
		} else if (elemType.contains("风")) {
			String WindDisp = "";
			double Totalwind = 0;
			String maxSta = "";
			String minSta = "";
			double minwind = resultList.get(0).getWinds();
			minSta = resultList.get(0).getStationName();
			double maxwind = resultList.get(resultList.size() - 1).getWinds();
			maxSta = resultList.get(resultList.size() - 1).getStationName();
			double avgwind = 0;
			int flag = 0;
			for (int i = 0; i < resultList.size(); i++) {
				double winds = resultList.get(i).getWinds();
				if (winds != -65535) {
					flag++;
					Totalwind = Totalwind + winds;
				}
			}
			avgwind = Totalwind / flag;
			String strTemp = String.format("%.1f", avgwind);
			avgwind = Double.valueOf(strTemp);

			//根据监测显示，时间（例如2019年11月19日15时），据全市111个区域自动气象站资料统计，最高温度35℃（XX),最低温度32℃（XX），全市平均温度30℃。
			if (!strStartDate.equals(strEndDate)) {
				WindDisp = String.format("根据监测显示，%s至%s,据全市%s个区域自动气象站资料统计，最大风速为%sm/s,出现在%s。", strStartDate, strEndDate, resultList.size(), maxwind, maxSta);

			} else {
				WindDisp = String.format("根据监测显示，%s,据全市%s个区域自动气象站资料统计，最大风速为%sm/s,出现在%s。", strStartDate, resultList.size(), maxwind, maxSta);

			}
			result = WindDisp;
		} else if (elemType.contains("湿")) {
			String HumidDisp = "";
			double Totalhumid = 0;
			String maxSta = "";
			String minSta = "";
			double minhumid = resultList.get(0).getHumid();
			minSta = resultList.get(0).getStationName();
			double maxhumid = resultList.get(resultList.size() - 1).getHumid();
			maxSta = resultList.get(resultList.size() - 1).getStationName();
			double avghumid = 0;
			int flag = 0;
			for (int i = 0; i < resultList.size(); i++) {
				double humid = resultList.get(i).getHumid();
				if (humid != -65535) {
					flag++;
					Totalhumid = Totalhumid + humid;
				}
			}
			avghumid = Totalhumid / flag;
			String strTemp = String.format("%.1f", avghumid);
			avghumid = Double.valueOf(strTemp);
			//根据监测显示，时间（例如2019年11月19日15时），据全市111个区域自动气象站资料统计，最高温度35℃（XX),最低温度32℃（XX），全市平均温度30℃。
			if (!strStartDate.equals(strEndDate)) {
				HumidDisp = String.format("根据监测显示，%s至%s,据全市%s个区域自动气象站资料统计，最小相对湿度%s%%,出现在%s。", strStartDate, strEndDate, resultList.size(), minhumid, minSta);

			} else {
				HumidDisp = String.format("根据监测显示，%s,据全市%s个区域自动气象站资料统计，最小相对湿度%s%%,出现在%s。", strStartDate, resultList.size(), minhumid, minSta);

			}
			result = HumidDisp;
		}
		return result;
	}

	private List<ActualData> qxElementQuery(ActualElemQuery elemQuery) {
		List<ActualData> resultList = new ArrayList<>();
		List<MsgMediumSmallScale> dataList = new ArrayList<>();
		Map<String, String> selectParam = new HashMap<>();
		RequestDataBySelect selectRequest = new RequestDataBySelect();
		String element = elemQuery.getElement();
		String type = elemQuery.getType();
		Date startDate = elemQuery.getStartDate();
		Date endDate = elemQuery.getEndDate();
		List<String> countys = elemQuery.getCountys();
		// 拼接where字段
		StringBuilder strWhere = new StringBuilder();
		int whereCount = 0;
		if (startDate != null) {
			whereCount++;
			strWhere.append(String.format("observTime >'%tF %tT'", startDate, startDate));
		}
		if (endDate != null) {
			strWhere.append(String.format(" and observTime <='%tF %tT'", endDate, endDate));
		}
		if (countys != null && countys.size() > 0) {
			strWhere.append(" and city like (");
			String tempString = "";
			for (String county : countys) {
				tempString += String.format("'%%%s%%',", county);
			}
			strWhere.append(tempString.substring(0, tempString.length() - 1) + ")");
		}
		// 获取查询字段
		List<String> columns = new ArrayList<String>();
		columns.add("stationid");// pg字段大小写不敏感的话，默认全部转换成小写模式
		columns.add("stationname");
		columns.add("longitude");
		columns.add("latitude");
		if (element != null && element.equals("rain")) {
			// 雨量和统计
			if (type != null && type.equals("sum")) {
				columns.add("sum(rain) as rain");
				selectRequest.setSort(new String[]{"rain desc"});
				strWhere.append(" and rain <> -65535");
			}
			// 表格统计
			if (type != null && (type.equals("spline") || type.equals("column"))) {
				if (elemQuery.getDaytype() != null && elemQuery.getDaytype().contains("日均")) {
					columns.add("to_char(observtime,'yyyy-MM-dd') as datechar");
					columns.add("sum(rain) as rain");
					strWhere.append(" and rain <> -65535");
					selectRequest.setSort(new String[]{"to_char(observtime,'yyyy-MM-dd')"});
				} else {
					columns.add("observtime");
					columns.add("rain");
					strWhere.append(" and rain <> -65535");
					selectRequest.setSort(new String[]{"observtime"});
				}
			}
		}
		if (element != null && element.equals("temp")) {
			// 温度统计
			if (type != null) {
				if (type.equals("avg")) {
					columns.add("cast(" + type + "(cast(DryBulbTemp as numeric(18,1))) as FLOAT) as DryBulbTemp");
					strWhere.append(" and DryBulbTemp <> -65535");
					selectRequest.setSort(new String[]{"DryBulbTemp "});
				} else if (type.equals("min")) {
					columns.add("cast(" + type + "(cast(mintemp as numeric(18,1))) as FLOAT) as mintemp");
					strWhere.append(" and mintemp <> -65535");
					selectRequest.setSort(new String[]{"mintemp "});
				} else {
					columns.add("cast(" + type + "(cast(maxtemp as numeric(18,1))) as FLOAT) as maxtemp");
					strWhere.append(" and maxtemp <> -65535");
					selectRequest.setSort(new String[]{"maxtemp "});
				}

			}

			// 表格统计
			if (type != null && (type.equals("spline") || type.equals("column"))) {
				if (elemQuery.getDaytype() != null && elemQuery.getDaytype().contains("日均")) {
					columns.add("to_char(observtime,'yyyy-MM-dd') as datechar");
					columns.add("avg(DryBulbTemp) as DryBulbTemp");
					strWhere.append(" and DryBulbTemp <> -65535");
					selectRequest.setSort(new String[]{"to_char(observtime,'yyyy-MM-dd')"});
				} else {
					columns.add("observtime");
					columns.add("DryBulbTemp");
					strWhere.append(" and DryBulbTemp <> -65535");
					selectRequest.setSort(new String[]{"observtime"});
				}
			}
		}
		if (element != null && element.equals("wind")) {
			// 风速统计
			if (type != null) {
				if (type.equals("avg")) {            //整点风
					columns.add(type + "(InstantWindV) as InstantWindV");
					columns.add("instantwindd");
					strWhere.append(" and InstantWindV <> -65535");
					strWhere.append(" and instantwindd <> -65535");
					selectRequest.setSort(new String[]{"InstantWindV "});
				} else        //极大风
				{
					columns.add(type + "(HExMaxWindV) as HExMaxWindV");
					columns.add("HExMaxWindd");
					strWhere.append(" and HExMaxWindV <> -65535");
					strWhere.append(" and HExMaxWindV <> -65535");
					selectRequest.setSort(new String[]{"HExMaxWindV "});
				}
			}
			// 表格统计
			if (type != null && (type.equals("spline") || type.equals("column"))) {
				if (elemQuery.getDaytype() != null && elemQuery.getDaytype().contains("日均")) {
					columns.add("to_char(observtime,'yyyy-MM-dd') as datechar");
					columns.add("avg(InstantWindV) as InstantWindV");
					strWhere.append(" and InstantWindV <> -65535");
					selectRequest.setSort(new String[]{"to_char(observtime,'yyyy-MM-dd')"});
				} else {
					columns.add("observtime");
					columns.add("InstantWindV");
					strWhere.append(" and InstantWindV <> -65535");
					selectRequest.setSort(new String[]{"observtime"});
				}
			}
		}
		if (element != null && element.equals("humid")) {
			// 湿度统计
			if (type != null) {
				if (type.equals("avg")) //相对湿度
				{
					columns.add("cast(" + type + "(RelHumidity) as integer) as RelHumidity");
					strWhere.append(" and RelHumidity <> -65535");
					selectRequest.setSort(new String[]{"RelHumidity "});
				} else {             //最小相对湿度
					columns.add("cast(" + type + "(minrelhumidity) as integer) as minrelhumidity");
					strWhere.append(" and minrelhumidity <> -65535");
					selectRequest.setSort(new String[]{"minrelhumidity "});
				}
			}
			// 表格统计
			if (type != null && (type.equals("spline") || type.equals("column"))) {
				if (elemQuery.getDaytype() != null && elemQuery.getDaytype().contains("日均")) {
					columns.add("to_char(observtime,'yyyy-MM-dd') as datechar");
					columns.add("cast(avg(RelHumidity)as integer) as RelHumidity");
					strWhere.append(" and RelHumidity <> -65535");
					selectRequest.setSort(new String[]{"to_char(observtime,'yyyy-MM-dd')"});
				} else {
					columns.add("observtime");
					columns.add("RelHumidity");
					strWhere.append(" and RelHumidity <> -65535");
					selectRequest.setSort(new String[]{"observtime"});
				}
			}
		}
		if (element != null && element.equals("pressure")) {
			// 气压统计
			if (type != null && type.equals("sum") || type.equals("avg") || type.equals("min") || type.equals("max")) {
				columns.add(type + "(StationPress) as StationPress");
				strWhere.append(" and StationPress <> -65535");
				selectRequest.setSort(new String[]{"StationPress desc"});
			}
			// 表格统计
			if (type != null && (type.equals("spline") || type.equals("column"))) {
				if (elemQuery.getDaytype() != null && elemQuery.getDaytype().contains("日均")) {
					columns.add("to_char(observtime,'yyyy-MM-dd') as datechar");
					columns.add("avg(StationPress) as StationPress");
					strWhere.append(" and StationPress <> -65535");
					selectRequest.setSort(new String[]{"to_char(observtime,'yyyy-MM-dd')"});
				} else {
					columns.add("observtime");
					columns.add("StationPress");
					strWhere.append(" and StationPress <> -65535");
					selectRequest.setSort(new String[]{"observtime"});
				}
			}
		}
		if (element != null && element.equals("visibility")) {
			// 能见度统计
			if (type != null && type.equals("sum") || type.equals("avg") || type.equals("min") || type.equals("max")) {
				columns.add(type + "(visibility) as visibility");
				strWhere.append(" and visibility <> -65535");
				selectRequest.setSort(new String[]{"visibility asc"});
			}
			// 表格统计
			if (type != null && (type.equals("spline") || type.equals("column"))) {
				if (elemQuery.getDaytype() != null && elemQuery.getDaytype().contains("日均")) {
					columns.add("to_char(observtime,'yyyy-MM-dd') as datechar");
					columns.add("avg(visibility) as visibility");
					strWhere.append(" and visibility <> -65535");
					selectRequest.setSort(new String[]{"to_char(observtime,'yyyy-MM-dd')"});
				} else {
					columns.add("observtime");
					columns.add("visibility");
					strWhere.append(" and visibility <> -65535");
					selectRequest.setSort(new String[]{"observtime"});
				}
			}
		}
		selectRequest.setColumns(columns.toArray(new String[columns.size()]));
		if (whereCount == 0 && !StringUtil.IsNullOrEmpty(strWhere.toString())) {
			strWhere = strWhere.replace(0, 4, "");
		}
		selectRequest.setParam(strWhere.toString());
		try {
			if (DateTime.UserMainDataTable(elemQuery.getStartDate(), DbConfig.CACHEDAYS)) {
				selectParam.put("method", "msgmediumsmallscale");
			} else {
				selectParam.put("method", "msgmediumsmallscale");
			}
			selectParam.put("sqlType", "select");
			selectParam.put("param", JsonUtil.object2Json(selectRequest));
			String message = pc.processRequest(selectParam);
			dataList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<MsgMediumSmallScale>>() {
			});
		} catch (Exception e) {
			// TODO: handle exception
			System.err.println(e.getStackTrace());
		}
		// 赋值
		try {

			WebCtrlData webCtrlData = new WebCtrlData();
			if (dataList.size() > 0) {
				for (MsgMediumSmallScale data : dataList) {
					ActualData actualData = new ActualData();
					actualData.setStationId(data.getStationid().trim());
					actualData.setStationName(data.getStationname().trim());
					actualData.setLon(data.getLongitude());
					actualData.setLat(data.getLatitude());
					DmMapPoint dmMapPoint = transformService.LonLatConvertToLambert(data.getLongitude(), data.getLatitude());
					actualData.setX(dmMapPoint.x);
					actualData.setY(dmMapPoint.y);
					switch (element) {
						case "rain":
							actualData.setRain(Double.parseDouble(String.format("%.1f", data.getRain())));
							break;
						case "temp":
							if (type.equals("avg")) {
								actualData.setTemp(Double.parseDouble(String.format("%.1f", data.getDrybulbtemp())));
							} else if (type.equals("min")) {
								actualData.setTemp(Double.parseDouble(String.format("%.1f", data.getMintemp())));
							} else {
								actualData.setTemp(Double.parseDouble(String.format("%.1f", data.getMaxtemp())));
							}
							break;
						case "humid":
							if (type.equals("avg")) {
								actualData.setHumid(Double.parseDouble(String.format("%d", data.getRelhumidity())));
							} else {
								actualData.setHumid(Double.parseDouble(String.format("%d", data.getMinrelhumidity())));
							}

							break;
						case "wind":
							if (type.equals("avg")) {      //整点
								actualData.setWinds(Double.parseDouble(String.format("%.1f", data.getInstantwindv())));
								String s = webCtrlData.GetAllFx(data.getInstantwindd().toString());
								actualData.setWinddirect(s);
								int i = webCtrlData.FengSuToFengJi(data.getInstantwindv());
								actualData.setWindvelocity(i);
							} else             //极大
							{
								actualData.setWinds(Double.parseDouble(String.format("%.1f", data.getHexmaxwindv())));
								String s = webCtrlData.GetAllFx(data.getHexmaxwindd().toString());
								actualData.setWinddirect(s);
								int i = webCtrlData.FengSuToFengJi(data.getHexmaxwindv());
								actualData.setWindvelocity(i);
							}

							break;
						case "pressure":
							actualData.setPressure(Double.parseDouble(String.format("%.1f", data.getStationpress())));
							break;
						default:
							break;
					}
					if (elemQuery.getDaytype() != null && elemQuery.getDaytype().contains("日均")) {
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
						actualData.setDateTime(sdf.parse(data.getDatechar()));
					} else {
						actualData.setDateTime(data.getObservtime());
					}
					resultList.add(actualData);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return resultList;
	}

	@Override
	public List<ContourImg> getRadarList(String type, String yj, String station, String url, String localPath,
			String application) {
		ArrayList<ContourImg> radarImgList = new ArrayList<ContourImg>();
		try {
			String collectionName = "ld_jpg_file";
			if (application.equals("gt")) {
				collectionName = "ld_gt_file";
			}
			Map<String, String> selectParam = new HashMap<String, String>();
			RequestDataBySelect selectRequest = new RequestDataBySelect();
			List<String> columns = new ArrayList<String>();
			columns.add("DateChar");
			columns.add("TimeChar");
			selectRequest.setColumns(columns.toArray(new String[columns.size()]));
			selectRequest.setParam(String.format("StationId = '%s' AND ldType = '%s' AND Elevation = '%s' AND State = '1'", station, type, yj));
			selectRequest.setSort(new String[]{"DateChar DESC","TimeChar DESC"});
			selectRequest.setLimit(10);
			selectParam.put("method", "potential_points");
			selectParam.put("sqlType", "select");
			selectParam.put("param", JsonUtil.object2Json(selectRequest));
			selectParam.put("advCode", DbConfig.advCode);
			String message = pc.processRequest(selectParam);
			List<Doppler> dopplerList
					= JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<Doppler>>() {
			});
			for (Doppler doppler : dopplerList) {
				DateTime date = new DateTime(doppler.getDateChar());
				String dateChar = date.toDateString();
				ContourImg img = new ContourImg();
				img.setType(type + "_" + yj + "_");
				String fileName = img.getType() + date.toDateTimeString("yyyyMMdd") + doppler.getTimeChar().trim() + "00"
						+ "gt.jpg";
				String PhysicUrl = localPath + fileName;
				// 当图片上传url存在并且图片review url不存在时
				File file = new File(PhysicUrl);
				if (!file.exists()) {
					Map<String, Object> queryMap = new HashMap<String, Object>();
					queryMap.put("ldtype", type.trim());
					queryMap.put("advCode", DbConfig.advCode);
					queryMap.put("datechar",  dateChar);
					queryMap.put("timechar",  doppler.getTimeChar().trim());
					queryMap.put("elevation",  yj);
					queryMap.put("stationid",  DbConfig.radarid);
					queryMap.put("collectionName", collectionName);
					byte[] data = ms.selectData(queryMap);
					if (data == null) {
						img.setName("images/tourinfo/index/暂无图片.jpg_" + date.toDateTimeString("yyyyMMdd")
								+ doppler.getTimeChar().trim() + "00");
					} else {
						FileUtil.bytesToFile(data, PhysicUrl);
						img.setName(url + fileName);
					}
				} else {
					img.setName(url + fileName);
				}
				radarImgList.add(img);


			}
			Collections.reverse(radarImgList);// 得到雷达图集合,反转排序
		} catch (Exception e) {
			e.printStackTrace();
		}
		return radarImgList;
	}


	@Override
	public List<ContourImg> getYTList(String type, String url, String localPath) {
		ArrayList<ContourImg> ytImgList = new ArrayList<ContourImg>();
		try {
			RequestDataBySelect dataSelect = new RequestDataBySelect();
			dataSelect.setColumns(new String[] { "datechar", "timechar" });
			dataSelect.setParam("yttype='" + type + "'");
			dataSelect.setLimit(10);
			dataSelect.setSort(new String[] { "datechar DESC", "timechar DESC" });
			Map<String, String> map = new HashMap<String, String>();
			map.put("param", JsonUtil.object2Json(dataSelect));
			map.put("method", "satellitenephoram");
			map.put("sqlType", "select");
			result = pc.processRequest(map);
			List<satellitenephoram> list = JsonUtil.jsonStr2TypeReference(result,
					new TypeReference<List<satellitenephoram>>() {
					});
			for (satellitenephoram item : list) {
				try {
					DateTime date = new DateTime(item.getDatechar());
					String dateChar = date.toDateString();
					ContourImg img = new ContourImg();
					img.setType(type + "_");
					String fileName = img.getType() + date.toDateTimeString("yyyyMMdd")
							+ item.getTimechar().trim() + "00" + ".jpg";
					String PhysicUrl = localPath + fileName;
					// 当图片上传url存在并且图片review url不存在时
					File file = new File(PhysicUrl);
					if (!file.exists()) {
						// 下载
							Map<String, Object> queryMap = new HashMap<String, Object>();
							queryMap.put("yttype", type.trim());
							queryMap.put("advCode", DbConfig.advCode);
							queryMap.put("datechar",  dateChar);
							queryMap.put("timechar",  item.getTimechar().toString().trim());
							queryMap.put("collectionName", "yt_jpg_file");
							byte[] data = ms.selectData(queryMap);
							if (data == null) {
								img.setName("images/tourinfo/index/暂无图片.jpg_" + date.toDateTimeString("yyyyMMdd")
										+ item.getTimechar().toString().trim() + "00");
							} else {
								FileUtil.bytesToFile(data, PhysicUrl);
								img.setName(url + fileName);
							}
					} else {
						img.setName(url + fileName);
					}
					ytImgList.add(img);
				} catch (Exception e) {

				}
			}
			Collections.reverse(ytImgList);// 得到雷达图集合
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ytImgList;
	}

	@Override
	public List<tour_actual_img> getSjtupian(String urlPath, String localPath, String stationname,HttpServletRequest request) {
		String result = "";
		String serviceFilePath = "";
		List<tour_actual_img> result1 = new ArrayList<tour_actual_img>();
		try {
			RequestDataBySelect dataBySelect = new RequestDataBySelect();
			dataBySelect.setColumns(new String[]{"stationid,dateChar,stationname,imagename"});
			dataBySelect.setParam("stationname='" + stationname + "'");
			dataBySelect.setSort(new String[]{"dateChar desc"});
			Map<String, String> map = new HashMap<String, String>();
			map.put("param", JsonUtil.object2Json(dataBySelect));
			map.put("method", "tour_actual_img");
			map.put("advCode", DbConfig.advCode);
			map.put("sqlType", "select");
			result = pc.processRequest(map);
			if (result.equals("")) {
				result = "[]";
			}
			List<tour_actual_img> tourimg = new ArrayList<tour_actual_img>();
			tourimg = JsonUtil.jsonStr2TypeReference(result, new TypeReference<List<tour_actual_img>>() {
			});

			for (tour_actual_img temp : tourimg) {
				tour_actual_img img = new tour_actual_img();
				img.setDatechar(temp.getDatechar().substring(0, 19));
				img.setImagename(temp.getImagename());
				img.setStationid(temp.getStationid());
				img.setStationname(temp.getStationname());
				result1.add(img);
			}

			for (tour_actual_img picInfo : result1) {
				String fileName = picInfo.getStationid() + ".png";
				String urlpath ;
				if (operatingSystem.equals("Windows")){
				urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\tour\\";// 临时文件目录
				}else {
					urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/tour/";// 临时文件目录
				}

				serviceFilePath = urlpath + fileName;// 服务器文件
				FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
				FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
				// 当图片上传url存在并且图片review url不存在时,mongodb下载
				File file = new File(serviceFilePath);
				if (!file.exists()) {
					Map<String, Object> map1 = new HashMap<String, Object>();
					map1.put("stationid", picInfo.getStationid());
					map1.put("table_name", "tour_stations");
					map1.put("collectionName", "image_file");
					map.put("advCode", DbConfig.advCode);
					byte[] data = ms.selectData(map1);
					if (data == null) {
						serviceFilePath = "";
					} else {
						FileUtil.bytesToFile(data, serviceFilePath);
					}
					if (operatingSystem.equals("Windows")){
						picInfo.setImagename("Temp\\tour\\" + fileName);
					}else {
						picInfo.setImagename("Temp/tour/" + fileName);
					}

				} else {
					if (operatingSystem.equals("Windows")){
						picInfo.setImagename("Temp\\tour\\" + fileName);
					}else {
						picInfo.setImagename("Temp/tour/" + fileName);
					}
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result1;
	}

	@Override
	public ContourImg getFireList(String producttype, HttpServletRequest request) {
		String result = "";
		ContourImg fireimage = new ContourImg();
		Date nowtime = new Date();
  		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		String endtime = simpleDateFormat.format(nowtime) + " 23:59:59";
		String starttime = simpleDateFormat.format(nowtime) + " 00:00:00";
		try {
			//String producttype = "森林火险预报";
				RequestDataBySelect dataBySelect = new RequestDataBySelect();
				dataBySelect.setColumns(new String[]{"id"});
				String produc = "%.doc%";
				dataBySelect.setParam(String.format("producttype = '%s' and productname like '%s' and maketime>='%s' and maketime<='%s'", producttype, produc, starttime, endtime));//
				dataBySelect.setSort(new String[]{"id DESC"});
				dataBySelect.setLimit(1);
				Map<String, String> map = new HashMap<String, String>();
				map.put("param", JsonUtil.object2Json(dataBySelect));
				map.put("method", "base_product");
				map.put("advCode", DbConfig.advCode);
				map.put("sqlType", "select");
				result = pc.processRequest(map);
			if (result.equals("")) {
				result = "[]";
			}
			List<base_product> firelist = new ArrayList<base_product>();
			firelist = JsonUtil.jsonStr2TypeReference(result, new TypeReference<List<base_product>>() {
			});
			if (firelist.size() > 0) {
				for (base_product d : firelist) {

					String serviceFilePath = "";
					// 下载
					String productname = d.getProductname();
					String path = request.getContextPath();
					String basePath = DbConfig.IP + path
							+ "/Temp/baseProduct/";
					String serviceUrl = basePath+productname;

					String urlpath ;
					if (operatingSystem.equals("Windows")){
						 urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\baseProduct\\";
					}else {
						urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/baseProduct/";
					}

					serviceFilePath = urlpath+productname;// 服务器文件
					FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
					FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
					// 如果目录中不存在文件，下载雷达文件到temp目录
					File serviceFile = new File(serviceFilePath);// 服务器文件
					if (!serviceFile.exists()) {// 把文件上传到服务器
						Map<String, Object> queryMap = new HashMap<String, Object>();
						queryMap.put("id", d.getId().toString());
						queryMap.put("table_name", "base_product");
						queryMap.put("collectionName", "image_file");
						queryMap.put("advCode", DbConfig.advCode);
						byte[] data = ms.selectData(queryMap);
						if (data == null) {
							serviceFilePath = "";
						} else {
							FileUtil.bytesToFile(data, serviceFilePath);
						}
					}
					if (!serviceFilePath.equals("")) {
						serviceFilePath = serviceUrl;
					}

					String imagepath = serviceFilePath;
					//添加视频路径
					fireimage.setName(imagepath);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return fireimage;


	}


	@Override
	public Date getheavyFcst() {
		//初始化重污染天气
		Date date = new Date();
		Map<String, String> selectParam = new HashMap<String, String>();
		RequestDataBySelect selectRequest = new RequestDataBySelect();
		String[] columns = new String[]{"to_char(time, 'yyyy-MM-dd HH24:MI:SS') as time"};
		selectRequest.setColumns(columns);
		selectRequest.setSort(new String[]{"time desc"});
		selectRequest.setLimit(1);
		try {
			selectParam.put("method", "heavy_forecast");
			selectParam.put("sqlType", "select");
			selectParam.put("param", JsonUtil.object2Json(selectRequest));
			String message  = pc.processRequest(selectParam);
			date = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<heavy_forecast>>() {
			}).get(0).getTime();
		} catch (Exception e) {
			// TODO: handle exception
		}
		return date;
	}

	@Override
	public List<heavy_forecast> getRGresult(String start_date, String type) {
		// TODO 手动判断重污染天气
		List<heavy_forecast> listData = new ArrayList<heavy_forecast>();
		Map<String, String> selectParam = new HashMap<String, String>();
		RequestDataBySelect selectRequest = new RequestDataBySelect();
		// 拼接where字段
		StringBuilder strWhere = new StringBuilder();
		if (!StringUtil.IsNullOrEmpty(start_date)) {
			strWhere.append(String.format(" and time='%s'", start_date));
		}
		if (!StringUtil.IsNullOrEmpty(type)) {
			strWhere.append(String.format(" and judgetype='%s'", type));
		}
		if (!StringUtil.IsNullOrEmpty(strWhere.toString())) {
			strWhere = strWhere.replace(0, 4, "");
		}
		selectRequest.setParam(strWhere.toString());
		try {
			selectParam.put("method", "heavy_forecast");
			selectParam.put("sqlType", "select");
			selectParam.put("param", JsonUtil.object2Json(selectRequest));
			String message = HttpRequest.get(DbConfig.qxConn, selectParam, true).body();
			listData = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<heavy_forecast>>() {
			});
		} catch (Exception e) {
			// TODO: handle exception
		}
		return listData;
	}
	@Override
	public ContourImg getProductImgList(String producttype,HttpServletRequest request) {
		String result = "";
		ContourImg fireimage = new ContourImg();
		Date nowtime = new Date();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		String endtime = simpleDateFormat.format(nowtime) + " 23:59:59";
		String starttime = simpleDateFormat.format(nowtime) + " 00:00:00";
		try {
			//String producttype = "景点森林火险预报";
			RequestDataBySelect dataBySelect = new RequestDataBySelect();
			dataBySelect.setColumns(new String[]{"id,bindid,productname"});
			String produc = "%.doc%";
			dataBySelect.setParam(String.format("producttype like '%s%%' and productname like '%s' and maketime>='%s' and maketime<='%s'", producttype, produc, starttime, endtime));//
			dataBySelect.setSort(new String[]{"id DESC"});
			dataBySelect.setLimit(1);
			Map<String, String> map = new HashMap<String, String>();
			map.put("param", JsonUtil.object2Json(dataBySelect));
			map.put("method", "base_product");
			map.put("advCode", DbConfig.advCode);
			map.put("sqlType", "select");
			result = pc.processRequest(map);
			if (result.equals("")) {
				result = "[]";
			}
			List<base_product> firelist = new ArrayList<base_product>();
			firelist = JsonUtil.jsonStr2TypeReference(result, new TypeReference<List<base_product>>() {
			});
			if (firelist.size() > 0) {
				if (producttype.contains("地质灾害")) {
					String bindid = firelist.get(0).getBindid().toString();
					String tableName = "dz_warning";
					dataBySelect = new RequestDataBySelect();
					dataBySelect.setColumns(new String[]{"warn_result"});
					dataBySelect.setSort(new String[]{"datechar DESC"});
					if (!StringUtil.IsNullOrEmpty(bindid)) {
						dataBySelect.setParam(String.format("docid='%s' and state>=2", bindid));//starttime
					}
					dataBySelect.setLimit(1);
					map = new HashMap<String, String>();
					map.put("param", JsonUtil.object2Json(dataBySelect));
					map.put("method", tableName);
					map.put("advCode", DbConfig.advCode);
					map.put("sqlType", "select");
					result = pc.processRequest(map);
					if (result.equals("")) {
						result = "[]";
					}
					List<dz_warning> listwarn = new ArrayList<dz_warning>();
					listwarn = JsonUtil.jsonStr2TypeReference(result, new TypeReference<List<dz_warning>>() {
					});
					if (listwarn.size() > 0) {
							String serviceFilePath = "";
							// 下载
							String fileName = firelist.get(0).getProductname().split("[.]")[0];
							String path = request.getContextPath();
							String basePath = DbConfig.IP + path
									+ "/Temp/product/";
							String serviceUrl = basePath + fileName;
						String urlpath ;
						if (operatingSystem.equals("Windows")){
							urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\product\\";
						}else {
							 urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/product/";
						}

							serviceFilePath = urlpath + fileName;// 服务器文件
							FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
							FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
							// 如果目录中不存在文件，下载雷达文件到temp目录
							File serviceFile = new File(serviceFilePath);// 服务器文件
							if (!serviceFile.exists()) {// 把文件上传到服务器
								Map<String, Object> queryMap = new HashMap<String, Object>();
								queryMap.put("id", firelist.get(0).getId()+"");
								queryMap.put("advCode", DbConfig.advCode);
								queryMap.put("table_name", "base_product");
								queryMap.put("collectionName", "image_file");
								byte[] data = ms.selectData(queryMap);
								if (data == null) {
									serviceFilePath = "";
								} else {
									FileUtil.bytesToFile(data, serviceFilePath);
								}
							}
							if (!serviceFilePath.equals("")) {
								serviceFilePath = serviceUrl;
							}

							String imagepath = serviceFilePath;
							//添加视频路径
						fireimage.setName(imagepath);
					}
				} else {
					for (base_product d : firelist) {
						String serviceFilePath = "";
						// 下载
						String fileName = d.getProductname().split("[.]")[0];
						String path = request.getContextPath();
						String basePath = DbConfig.IP + path
								+ "/Temp/product/";
						String serviceUrl = basePath + fileName;
						String urlpath ;
						if (operatingSystem.equals("Windows")){
							 urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\product\\";
						}else {
							urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/product/";
						}

						serviceFilePath = urlpath + fileName;// 服务器文件
						FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
						FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
						// 如果目录中不存在文件，下载雷达文件到temp目录
						File serviceFile = new File(serviceFilePath);// 服务器文件
						if (!serviceFile.exists()) {// 把文件上传到服务器
							Map<String, Object> queryMap = new HashMap<String, Object>();
							queryMap.put("id", d.getId()+"");
							queryMap.put("advCode", DbConfig.advCode);
							queryMap.put("table_name", "base_product");
							queryMap.put("collectionName", "image_file");
							byte[] data = ms.selectData(queryMap);
							if (data == null) {
								serviceFilePath = "";
							} else {
								FileUtil.bytesToFile(data, serviceFilePath);
							}
						}
						if (!serviceFilePath.equals("")) {
							serviceFilePath = serviceUrl;
						}

						String imagepath = serviceFilePath;
						//添加视频路径
						fireimage.setName(imagepath);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}


		return fireimage;
	}

	@Override
	public ContourImg getYBDZTList(String element, String url, String localPath,String date) {
			String el = element;
			String ele = el;
			String ntimes ="024";
			String timechar = "08";
			String collectType = "";
			String description = "";
			String timeType = "1";
			ContourImg result = new ContourImg();
			try {
				if (el.contains("降水量")) {
					collectType = "rain";
					if (el.equals("雨量")) {
						timeType = "1";
					} else if (el.contains("三")) {
						timeType = "3";
					} else if (el.contains("六")) {
						timeType = "6";
					} else if (el.contains("十二")) {
						timeType = "12";
					} else if (el.contains("二十四")) {
						timeType = "24";
					} else {
						timeType = "1";
					}
				}

				if (el.contains("温")) {

					collectType = "temp";
					if (el.contains("平均")) {
						ele = "温度";
					} else if (el.contains("最高")) {
						ele = "最高温";
					} else if (el.contains("最低")) {
						ele = "最低温";
					}

				}
				if (el.contains("风")) {
					if (el.contains("整点")) {
						ele = "风速";
					} else if (el.contains("极大")) {
						ele = "极大风速";
					}
					collectType = "wind";
				}
				if (el.contains("湿")) {
					if (el.equals("相对湿度")) {
						ele = "湿度";
					} else if (el.equals("最小相对湿度")) {
						ele = "最小相对湿度";
					}
					collectType = "humid";
				}
				if (el.contains("气")) {
					collectType = "press";
				}
				// 类型不为空
				if (!collectType.equals("")) {
					int index = 0;
					ContourImg contourImg = new ContourImg();
					int i = 0;
					DateTime dateTime = DateTime.parseDateTime(DateTime.now().toDateTimeString());//  括号里面原来内容 2019-05-19 12:00:00
					for (i = 0; i < 3; i++) {
						dateTime = dateTime.AddHours(-i);
						String fileName = el+ "预报" + dateTime.toDateTimeString("yyyyMMddHH0000") + ".jpg";
						File file = new File(localPath + fileName);
						if (!file.exists()) {
							// 从mongdb获取图片
							Map<String, Object> map1 = new HashMap<String, Object>();
							map1.put("type", ele);
							map1.put("timechar", timechar);
							map1.put("ntimes",ntimes);
							map1.put("datechar", dateTime.toDateTimeString("yyyy-MM-dd"));//查询最新时间数据
							//map1.put("datechar", date);//数据库存在的时间，前端传递得时间，确保能查到数据
							map1.put("collectionName", "yb_" + collectType + "_jpg_file");
							map1.put("advCode", DbConfig.advCode);
							byte[] data = ms.selectData(map1);
							if (data != null) {
								contourImg.setType(el);
								contourImg.setName(url + fileName);
								// description = getSKDZTQuery(collectType, el, timeType, dateTime);
								// contourImg.setDescription(description);
								result = contourImg;
								FileUtil.bytesToFile(data, localPath + fileName);
								index++;
								break;
							} else {
								contourImg.setType(el);
								contourImg.setName("images/tourinfo/none.jpg");
								contourImg.setDescription("");
								result = contourImg;
							}
						} else {
							contourImg.setType(el);
							contourImg.setName(url + fileName);
							// description = getSKDZTQuery(collectType, el, timeType, dateTime);
							// contourImg.setDescription(description);
							result = contourImg;
							index++;
							break;
						}
					}
					if (i == 3) {
						result = contourImg;
						index++;
					}
				}
				// }
			} catch (Exception e) {
				e.printStackTrace();
			}

			return result;
		}



}
